将多个对象推入单个对象

时间:2017-08-29 15:56:24

标签: javascript arrays json javascript-objects

我正在考虑将多个Json对象推送到一个单个对象中。

目前我正在从AJAX解析一个数组,并且像这样控制日志

0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", …}
1:{id: "25", user: "Jim", pass: "pass", name: "Jim Bloggs", role: "Technical Support", …}
2:{id: "26", user: "John", pass: "pass", name: "John Bloggs", role: "Technical Support", …}

我需要运行循环并将所有ID和用户推送到一行,格式为

0: {Joe : 24, Jim : 25, John : 26}

我该怎么做?

由于

1 个答案:

答案 0 :(得分:2)

您可以将数据缩减为新对象:



let a = [{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support"},
{id: "25", user: "Jim", pass: "pass", name: "Jim Bloggs", role: "Technical Support"},
{id: "26", user: "John", pass: "pass", name: "John Bloggs", role: "Technical Support"}]

let res = a.reduce((a,b) => {
    a[b.user] = b.id;
    return a;
}, {});

console.log(res);




或者如果您更喜欢解构



let a = [{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support"},
{id: "25", user: "Jim", pass: "pass", name: "Jim Bloggs", role: "Technical Support"},
{id: "26", user: "John", pass: "pass", name: "John Bloggs", role: "Technical Support"}]

let res = {};
for (let {id, user} of a) {
    res[user] = id;
}

console.log(res);