在JavaScript中结合两个不同大小的对象数组

时间:2018-09-20 09:40:55

标签: javascript ecmascript-6

我有两个这样大小不同的数组

[{ id: 1, name: 'One', contacts: [] }, 
 { id: 2, name: 'Two', contacts: [] }, 
 { id: 3, name: 'Three', contacts: [] }, 
 { id: 4, name: 'Four', contacts: [] }]

[{ id: 1, name: 'One', contacts: [{ id: 100, name: "C1" }, { id: 101, name: "C2" }] },
 { id: 3, name: 'Three', contacts: [{ id: 120, name: "C1" }, { id: 121, name: "C2" }] },
 { id: 5, name: 'Five', contacts: [{ id: 420, name: "F1" }, { id: 421, name: "F2" }] }];

我尝试使用javascript中的以下代码

const mergeArray = (source, merge, by) => source.map(item => ({
    ...item,
    ...(merge.find(i => i[by] === item[by]) || {}),
    }));

    output =  mergeArray(this.oldArray1,this.oldArray2,'id');

它将输出显示为

[{ id: 1, name: 'One', contacts: [{ id: 100, name: "C1" }, { id: 101, name: "C2" }] }, 
{ id: 2, name: 'Two', contacts: [] }
{ id: 3, name: 'Three', contacts: [{ id: 120, name: "C1" }, { id: 121, name: "C2" }] }]

但需要这样的输出

[{ id: 1, name: 'One', contacts: [{ id: 100, name: "C1" }, { id: 101, name: "C2" }] }, 
{ id: 2, name: 'Two', contacts: [] }
{ id: 3, name: 'Three', contacts: [{ id: 120, name: "C1" }, { id: 121, name: "C2" }] },
{ id: 4, name: 'Four', contacts: [] }
{ id: 5, name: 'Five', contacts: [{ id: 420, name: "F1" }, { id: 421, name: "F2" }] }]

1 个答案:

答案 0 :(得分:1)

您可以将数组收集到一个数组中,或者简单地合并这些数组,然后通过检入id是否在结果数组中来缩小该数组。如果未将对象添加到结果数组中或存在,则使用实际数据扩展contacts

var array1 = [{ id: 1, name: 'One', contacts: [] }, { id: 2, name: 'Two', contacts: [] }, { id: 3, name: 'Three', contacts: [] }, { id: 4, name: 'Four', contacts: [] }],
    array2 = [{ id: 1, name: 'One', contacts: [{ id: 100, name: "C1" }, { id: 101, name: "C2" }] }, { id: 3, name: 'Three', contacts: [{ id: 120, name: "C1" }, { id: 121, name: "C2" }] }, { id: 5, name: 'Five', contacts: [{ id: 420, name: "F1" }, { id: 421, name: "F2" }] }],
    merged = [array1, array2].reduce((r, a) => {
        a.forEach(o => {
            var object = r.find(({ id }) => id === o.id);
            if (!object) {
                return r.push(o);
            }
            object.contacts.push(...o.contacts);
        });
        return r;
    }, []);

console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }