我有一个像这样的数组:
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/