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
Well, assuming the JSON has already been parsed to an Object
:
var data = JSON.parse('{"status":"success","employees":[{},{},{}]}'); // abridged
You can loop over data.employees
to build the "dictionary" (Object
):
var employees = {};
for (var i = 0; i < data.employees.length; i++) {
employees[data.employees[i].id] = data.employees[i];
}
Then, given an employeeId
:
var employee = employees[employeeId];
Note that that is not valid JSON: you have to use double-quotes, not single-quotes.
Assuming you fix that, and that the JSON has already been retrieved into a string variable jsonResult
, you need to parse that to get an object using JSON.parse():
var result = JSON.parse(jsonResult);
You can build a dictionary from there:
var employees = {};
for (var i = 0, emp; i < result.employees.length; i++) {
emp = result.employees[i];
employees[ emp.id ] = emp;
}
console.log(employees[56].name); // logs "Harry"
console.log(employees[56].department); // logs "marketing"
You said "and the value is the (say) name" - if you don't need the department
values then in the for loop above say employees[ emp.id ] = emp.name;
and then (obviously) employees[56]
would give you "Harry" directly.
Demo: http://jsfiddle.net/RnmFn/1/
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
}
You could write a javascript function to get an employee by id from a list of employees:
function getEmployee(id, employees) {
for (var i = 0; i < employees.length; i++) {
var employee = employees[i];
if (employee.id === id) {
return employee;
}
}
return null;
}
and then use this function on the response you got from the server after parsing the JSON string back to a javascript object:
var json = 'the JSON string you got from the server';
var obj = JSON.parse(json);
var employees = obj.employees;
var employee = getEmployee(34, employees);
if (employee != null) {
alert(employee.name);
}