javascript 根据对象键合并单个数组的对象[已关闭]

y1aodyip  于 2023-02-11  发布在  Java
关注(0)|答案(2)|浏览(118)
    • 已关闭**。此问题为opinion-based。当前不接受答案。
    • 想要改进此问题吗?**请更新此问题,以便editing this post可以用事实和引文来回答。

2小时前关门了。
Improve this question
我很困惑合并数组内容从JavaScript。请帮助获得最好的方式来获得所需的结果。A我也尝试了其他方法提到的SO。

[
    {
        "Afghanistan": 2646432,
        "categories": "2018"
    },
    {
        "Afghanistan": 6545700,
        "categories": "2019"
    },
    {
        "Afghanistan": 7475886,
        "categories": "2020"
    },
    {
        "Albania": 740232,
        "categories": "2018"
    },
    {
        "Albania": 2374785,
        "categories": "2019"
    },
    {
        "Albania": 2180850,
        "categories": "2020"
    }
]

这是我的预期输出::
[ { "Afghanistan": 2646432, "Albania": 740232, "categories": "2018" }, { "Afghanistan": 6545700, "Albania": 2374785, "categories": "2019" }, { "Afghanistan": 7475886, "Albania": 2180850, "categories": "2020" } ]

busg9geu

busg9geu1#

array.reduce((acc, item) => {
    const found = acc.find(obj => obj.categories === item.categories);
    if (found) {
        Object.assign(found, item);
    } else {
        acc.push(item);
    }
    return acc;
}, [])
txu3uszq

txu3uszq2#

let list=[{Afghanistan:2646432,categories:"2018"},{Afghanistan:6545700,categories:"2019"},{Afghanistan:7475886,categories:"2020"},{Albania:740232,categories:"2018"},{Albania:2374785,categories:"2019"},{Albania:2180850,categories:"2020"},{India:2029282726,categories:"2022"},{India:2029282729,categories:"2023"},{Afghanistan:2029282729,categories:"2023"}];

let result = Object.values(list.reduce((acc, cur) => (acc[cur.categories] ? acc[cur.categories] = {...acc[cur.categories], ...cur} : acc[cur.categories] = cur, acc), {}));

console.log(result);

可以使用reduce方法

相关问题