我想合并两个数组。我想从arr2结构中得到arr1数据,我该怎么做?
我尝试使用3 forEach,但它不起作用。
const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}];
const arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}];
我想要下面的结果
newArr = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}]}]
const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}]
const arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}]
const r = [...new Set(arr2.map(i=>i.id))].map(id=>(({id, List})=>({id, List:List.filter(({name})=>arr2.some(i=>i.id===id && i.name===name))}))(arr1.find(i=>i.id===id)))
console.log(r)
如果您需要添加索引(按照下面的注释):
const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}]
const arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}]
const r = [...new Set(arr2.map(i=>i.id))].map((id,c)=>(({List})=>({id, List:List.filter(({name})=>arr2.some(({id:x, name:y})=>x===id && y===name)).map((i,d)=>({...i, index: `${c}-${d}`}))}))(arr1.find(({id:x})=>x===id)))
console.log(r)
这里有一个使用reduce的简单解决方案
const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}];
const arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}];
const res = arr2.reduce((a,v)=> {
const item = arr1.find(x=> x.id === v.id);
const tItem =a.find(x=> x.id == v.id) || {id: v.id, List:[]};
tItem.List = [...tItem.List,...item.List.filter(x=> x.name == v.name)]
a.push({...tItem});
return a;
},[])
console.log(res)