JSON to dictionary in JavaScript?

前端 未结 4 2107
我在风中等你
我在风中等你 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 03:55

    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/

提交回复
热议问题