基于一个公共键角度2合并2个阵列

时间:2017-01-18 10:06:18

标签: javascript arrays typescript merge

我在arrays中有2个Angular 2,我希望根据一个键值合并它们。

数组1:

[{"columnId":1,"type":"value 1"},{"columnId":2,"type":"value 2"}]

数组2:

[{"columnId":1,"field":"field 1"},{"columnId":2,"field":"field 2"}]

所以我想要最终结果

[{"columnId":1,"field":"field 1","type":"value 1"},{"columnId":2,"field":"field 2","type":"value 2"}]

1 个答案:

答案 0 :(得分:7)

这应该做你想要的:

const arr1 = [{"columnId":1,"type":"value 1"},{"columnId":2,"type":"value 2"}];
const arr2 = [{"columnId":1,"field":"field 1"},{"columnId":2,"field":"field 2"}];

const result = arr1.map(val => {
    return Object.assign({}, val, arr2.filter(v => v.columnId === val.columnId)[0]);
});

console.log(result);
// [{"columnId":1,"field":"field 1","type":"value 1"},{"columnId":2,"field":"field 2","type":"value 2"}]