gpt4 book ai didi

javascript - 基于一个公共(public)键angular 2合并2个数组

转载 作者:搜寻专家 更新时间:2023-10-30 20:54:52 25 4
gpt4 key购买 nike

我在 Angular 2 中有 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"}]

最佳答案

这应该做你想做的:

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"}]

关于javascript - 基于一个公共(public)键angular 2合并2个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com