JSON 到 JavaScript 中的字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17496513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:32:24  来源:igfitidea点击:

JSON to dictionary in JavaScript?

javascripttype-conversion

提问by Vivek Ragunathan

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:

在我的 JS 代码中,我需要将来自服务器的 JSON 响应转换为字典,以便我可以通过键名访问它们。这是情况:

Say, this is the JSON response from my server:

说,这是来自我的服务器的 JSON 响应:

{
   '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).

现在我需要的是创建一个字典变量,键是 id,值是(比如)名称,以便我可以访问它们 variable.id 或 variable[id_value](从循环中)。

How can this be achieved? Your help highly appreciated.

如何做到这一点?非常感谢您的帮助。

Thanks Vivek Ragunathan

感谢 Vivek Ragunathan

回答by nnnnnn

Note that that is not valid JSON: you have to use double-quotes, not single-quotes.

请注意,这不是有效的 JSON:您必须使用双引号,而不是单引号。

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():

假设你解决了这个问题,并且 JSON 已经被检索到一个字符串变量中jsonResult,你需要解析它以使用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 departmentvalues then in the for loop above say employees[ emp.id ] = emp.name;and then (obviously) employees[56]would give you "Harry" directly.

您说“并且值是(说)名称”-如果您不需要这些department值,那么在上面的 for 循环中说employees[ emp.id ] = emp.name;然后(显然)employees[56]会直接给您“Harry”。

Demo: http://jsfiddle.net/RnmFn/1/

演示:http: //jsfiddle.net/RnmFn/1/

回答by Jonathan Lonowski

Well, assuming the JSON has already been parsed to an Object:

好吧,假设 JSON 已经被解析为一个Object

var data = JSON.parse('{"status":"success","employees":[{},{},{}]}'); // abridged

You can loop over data.employeesto build the "dictionary" (Object):

您可以循环data.employees构建“字典”( Object):

var employees = {};

for (var i = 0; i < data.employees.length; i++) {
    employees[data.employees[i].id] = data.employees[i];
}

Then, given an employeeId:

然后,给定一个employeeId

var employee = employees[employeeId];

回答by Darin Dimitrov

You could write a javascript function to get an employee by id from a list of employees:

您可以编写一个 javascript 函数来通过员工列表中的 id 获取员工:

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:

然后在将 JSON 字符串解析回 javascript 对象后,对从服务器获得的响应使用此函数:

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

回答by CRice

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
}