Let say I have two array of objects.
var arr1= [
{
pid: [ '1967', '967' ],
},
{
pid: [ '910', '1967', '967' ],
},
{
pid: [ '967' ],
}
]
var arr2 = [
{ _id: '967', name: 'test pid' },
{ _id: '1967', name: 'test one test' },
{ _id: '910', name: 'this is test name' }
]
is there any way I can find the _id and name from array2 using the id from arr1 and replace element of arr1.pid. like below
arr1 = [
{
pid: [ { _id: '1967', name: 'test one test' }, { _id: '967', name: 'test pid' }],
},
{
pid: [ { _id: '910', name: 'this is test name' }, { _id: '1967', name: 'test one test' }, { _id: '967', name: 'test pid' } ],
},
{
pid: [ { _id: '967', name: 'test pid' } ],
}
]
so far I have done as below
for (var i = 0; i < arr1.length; i++){
var pids = arr1[i].pid
for(var j = 0; j<pids.length; j++){
var result = arr2.filter(obj => {
return obj._id === pids[j]
})
console.log(result) //can not push this into arr1['pid']
}
}
filterreturns the matching element(s) in an array. You want a single item so usefind.arr1 = arr1.map(x => ({pid: x.pid.map(id => arr2.find(obj => obj._id === id) || obj)}))