28

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 response from my server:

{
   'status': 'success',
   'employees' : [
      { 'id': 12, 'name': 'Tom', 'department': 'finance' },
      { 'id': 34, 'name': 'Dick', 'department': 'admin' },
      { 'id': 56, 'name': 'Harry', 'department': 'marketing' }
   ]
}

Now what i need is to create a dictionary variable such that the key is the id and the value is the (say) name so that i can access them variable.id or variable[id_value] (from a loop).

How can this be achieved? Your help highly appreciated.

Thanks

0

4 Answers 4

39

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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];

Comments

1

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

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.