JSON to dictionary in JavaScript?

前端 未结 4 2115
我在风中等你
我在风中等你 2020-12-31 03:34

In my JS code, I need to convert the JSON response from server to a dictionary so that I can access them by key names. Here is the situation:

Say, this is the JSON r

4条回答
  •  爱一瞬间的悲伤
    2020-12-31 04:09

    Something like this allows you to create a dictionary in one line, and specify the key and value used, or at least the key where the value becomes the entire object.

    function toDictionary(items, key, value) {
    
        var dictionary = {};
    
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                dictionary[key(item)] = value ? value(item) : item;
            }
        }
    
        return dictionary;
    }
    

    Example usage:

    var dictionary = toDictionary(result.employees, function (record) { return record.id; });
    var employee = dictionary[34];
    if (employee) {
      // do something with employee object
    }
    

提交回复
热议问题