在javascript中将JSON对象字符串数组转换为JS对象数组

时间:2017-04-06 12:22:58

标签: javascript json

我有一些数据,我已将其转换为对象数组,如:

[{"name": "aa", "birth":"19990101"},
{"name": "bb", "birth":"19990102"},
{"name": "cc", "birth":"19990103"}];

我想将其转换为这样的对象:

{"aa":"19990101","bb":"19990102","cc":"19990103"};

最好的方法是什么?谢谢!

4 个答案:

答案 0 :(得分:2)

您可以使用一些销毁并将值分配给给定的密钥。



var array = [{ name: "aa", birth: "19990101" }, { name: "bb", birth: "19990102" }, { name: "cc", birth: "19990103" }],
    object = array.reduce((r, { name, birth }) => (r[name] = birth, r), {});

console.log(object);




Object.assignspread syntax ...



var array = [{ name: "aa", birth: "19990101" }, { name: "bb", birth: "19990102" }, { name: "cc", birth: "19990103" }],
    object = Object.assign({}, ...array.map(({ name, birth }) => ({ [name]: birth })));

console.log(object);




答案 1 :(得分:1)

您只需使用reduce

即可
var x = [{"name": "aa", "birth":"19990101"},
{"name": "bb", "birth":"19990102"},
{"name": "cc", "birth":"19990103"}];

var result = x.reduce((a, b) => (a[b['name']] = b['birth'], a), {});

答案 2 :(得分:1)

试试这个

var a = [{"name": "aa", "birth":"19990101"},
{"name": "bb", "birth":"19990102"},
{"name": "cc", "birth":"19990103"}];

var map = {}; a.forEach( function(item){ map[item.name] = item.birth; })

console.log(map);

答案 3 :(得分:0)

另一种方式可能是:



var values =[
  {"name": "aa", "birth":"19990101"},
  {"name": "bb", "birth":"19990102"},
  {"name": "cc", "birth":"19990103"}
];

var result = [];

for(var i = 0; i < values.length; i++){
    var item = {};
    item[values[i].name] = values[i].birth;
    result.push(item);
}

console.log(result);
&#13;
&#13;
&#13;