Home > Enterprise >  How to join arr1 array and arr2 array (based on arr2 array structure)
How to join arr1 array and arr2 array (based on arr2 array structure)

Time:12-04

I want to merge two arrays. I want to get arr1 data based on arr2 structure, how should I do it?

I tried using 3 forEach, but it doesn't work.

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'}];

I want the result below

newArr = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}]}]

CodePudding user response:

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)

CodePudding user response:

Here is a simple solution using 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)

  • Related