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
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
}