将数组转换为键值对

时间:2017-05-04 09:32:20

标签: javascript arrays

我有一个数组

[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]

是否可以成为键值对?

{
"flight1" : "123",
"flight2" : "456"
}

5 个答案:

答案 0 :(得分:7)

您可以使用var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}] var result = arr.reduce(function(r, e) { r[e.field] = e.value; return r; }, {}); console.log(result)并返回对象作为结果。



var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
    result = Object.assign(...data.map(a => ({ [a.field]: a.value })));

console.log(result);




答案 1 :(得分:2)

您可以使用标准for循环: -

var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];

var obj = {};

for (var i = 0; i < data.length; i++)
    obj[data[i].field] = data[i].value;

console.log(obj);

答案 2 :(得分:0)

您可以映射键值对并将其指定给对象。

&#13;
&#13;
.ts
&#13;
&#13;
&#13;

答案 3 :(得分:0)

new Map()构造函数可以为您执行此操作:

var data = [
    {"field": "flight1", "value": "123"},
    {"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));

答案 4 :(得分:0)

这可能会在另一天帮助别人。我尝试了上面的所有示例,但每次控制台都给我这样的内容: { flight1: "123", flight2: "456" }

我的问题是我正在将序列化数组转换为很快导致许多微小问题。下面是无效的代码:

var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);

请注意,flight1和flight2丢失了双引号。以下是我的解决方案:

var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);

注意:这是使用电子框架

向数据库(neDB)提交用户信息的代码