Array > Object:如何使用 reduce 索引对象数组,在结果中省略嵌套元素的索引(es2017)?

Array > Object: how to index an array of objects with reduce, omitting the index from nested element in result (es2017)?

我有一个这样的数组:

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"
    }
}

我不知道如何以 terse/elegant 的方式完成同样的事情,以至于 id 被省略了。

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

你可以这样做: peopleArray.reduce( (ac, p) => ({...ac, [p.id]: { country : p.country } }), {} )

如果你想以 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 - 将能够对对象使用 Rest 参数

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