问题描述
我如何将这些合并到数组中, 如果 id 中存在重复项:我想将它们加在一起
const arr1 = [{id:'1',start:1,end:0},{id:'2',start:3,{id:'3',end:0}]
const arr2 = [{id:'4',start:0,end:4},end:4}]
我希望输出是这样的
const arr3 =[{id:'1',{id:'4',end:4}]
我是新来的,感谢所有的帮助! :)
解决方法
检查这个:
var window = remote.getCurrentWindow();
,
我认为如果 arr1 和 arr2 映射而不是数组,我认为这会更容易,假设 id 是唯一的:
const map1 = new Map(arr1.map(x => [x.id,{start: x.start,end: x.end}]))
const map2 = new Map(arr2.map(x => [x.id,end: x.end}]))
const intersection = [...map1.keys()].filter(x => map2.has(x))
const map3 = new Map([...map1,...map2])
intersection.forEach(key => map3.set(key,{start: map1.get(key).start + map2.get(key).start,end: map1.get(key).end + map2.get(key).end}))
console.log(map3)
0: 1 → Object { start: 1,end: 0 }
1: 2 → Object { start: 3,end: 4 }
2: 3 → Object { start: 1,end: 0 }
3: 4 → Object { start: 0,end: 4 }
,
https://jsfiddle.net/2j8eazkr/
const arr1 = [{id:'1',start:1,end:0},{id:'2',start:3,{id:'3',end:0}]
const arr2 = [{id:'4',start:0,end:4},end:4}]
//clone elements of first array
let arr3 = arr1.map(x => { return { id: x.id,start: x.start,end: x.end } });
//iterate second array and use it to update existing or add if its new
arr2.forEach(x => {
let y = arr3.find(_ => _.id === x.id);
if(y) y.end = x.end;
else arr3.push(x);
})