首页 > 解决方案 > 在 JavaScript 中根据 id 属性合并两个对象

问题描述

从响应中获取的原始数组:

result = [
    {
        id: 1,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 1,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    }
]

我想要下面提到的结果。请只做那些需要的。提前致谢

newResult = [
    {
        id: 1,
        newArr: [{
            a: "one",
            b: "two",
            c: "three",
            d: "four",
        }, {
            a: "five",
            b: "six",
            c: "seven",
            d: "eight",
        }]
    }
]

标签: javascript

解决方案


const obj = {};
result.forEach(t => obj[t.id] ? obj[t.id].push(t) : (obj[t.id] = [t]));
const transformed = Object.keys(obj).map(t => ({id: t, newArr: obj[t].map(el => 
{delete el.id; return el})}));
console.log(transformed);

result = [
    {
        id: 1,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 1,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    },
        {
        id: 3,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 2,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    },
        {
        id: 2,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 3,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    }
];
const obj = {};
result.forEach(t => obj[t.id] ? obj[t.id].push(t) : (obj[t.id] = [t]));
const transformed = Object.keys(obj).map(t => ({id: t, newArr: obj[t].map(el => {delete el.id; return el})}));
console.log(transformed);


推荐阅读