繁体   English   中英

数组>对象:如何使用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"
    }
}

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

寻找与Node.js版本8.11.1兼容的纯javascript es2017解决方案。

如果要使id为键的对象和object为value对象。 您可以尝试使用Rest参数遵循

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

您可以执行以下操作: peopleArray.reduce( (ac, p) => ({...ac, [p.id]: { country : p.country } }), {} )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM