javascript - 数组 > 对象 : how to index an array of objects with reduce, 省略结果中嵌套元素的索引(es2017)?

标签 javascript arrays javascript-objects ecmascript-2017

我有一个像这样的数组:

const peopleArray = [
    {
        "id": "Antoine",
        "country": "France"
    },
    {
        "id": "Alejandro",
        "country": "Spain"
    }
]

我想表示为像这样的对象(请注意 id 不是属性):

{
    "Antoine": {
        "country": "France"

    },
    "Alejandro": {
        "country": "Spain"
    }
}

到目前为止,我发现我可以做到这一点(优雅!):

peopleArray.reduce( (ac, p) => ({...ac, [p.id]: p }), {} )

产生:

{
    "Antoine": {
        "id": "Antoine",
        "country": "France"

    },
    "Alejandro": {
        "id": "Alejandro",
        "country": "Spain"
    }
}

我不知道如何以简洁/优雅的方式完成相同的任务,从而省略 id

正在寻找适用于 Node.js 版本 8.11.1 的纯 javascript es2017 解决方案。

最佳答案

如果您想以id作为键并以剩余对象作为value来创建和对象。您可以尝试使用Rest Parameters进行以下操作

ES2017

const peopleArray = [{"id": "Antoine","country": "France"},{"id": "Alejandro","country": "Spain"}];

const result = peopleArray.reduce( (ac, o) => { 
  ac[o.id] = Object.assign({}, o); 
  delete ac[o.id].id; 
  return ac; 
}, {});
console.log(result);

ES2018 - 将能够使用对象的静态参数

const peopleArray = [{"id": "Antoine","country": "France"},{"id": "Alejandro","country": "Spain"}];

const result = peopleArray.reduce( (ac, {id, ...rest}) => Object.assign(ac, {[id]: rest}), {} );
console.log(result);

关于javascript - 数组 > 对象 : how to index an array of objects with reduce, 省略结果中嵌套元素的索引(es2017)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946637/

相关文章:

java - 检索 WebService 数组 Java(Android)

javascript - 从对象外部向选项对象添加选项 - javascript

javascript - rails : View javascript object's attributes in browser's console

javascript - 更改倒计时持续时间

arrays - Golang问题数组数独-网格[i] [j] [0]

javascript - 如何检索包含句点的 JavaScript 属性

javascript - 如何在 JavaScript 对象数组中查找重复值,并只输出唯一值?

javascript - Json 编码 php mysql 查询

javascript - 在 JavaScript 中对时间戳数组进行排序

c - 关于在 C 中使用数组作为指针的问题