Home > Back-end >  comparing two arrays and match one key from first array's object in the second array's obj
comparing two arrays and match one key from first array's object in the second array's obj

Time:12-17

array1 = [
   {
     _id: new ObjectId("639979460a52134240478a9b"),
     taggedFileId: '6399798f0a52134240478abf'
   },
   {
     _id: new ObjectId("639b576c2743a77ea2812f07"),
     taggedFileId: '639988250a52134240478b07'
   }
 ]
 
 
 array2 = [
  {
    fileIds: new ObjectId("639979460a52134240478a9b"),
    rateResult: 'none',
    taggedFileId: '6399798f0a52134240478abf',
    _id: new ObjectId("639c8531dcd57c7d559e6211")
  },
  {
    fileIds: new ObjectId("639b576c2743a77ea2812f07"),
    rateResult: 'none',
    taggedFileId: '639988250a52134240478b07',
    _id: new ObjectId("639c8531dcd57c7d559e6212")
  }
]

I want to check in the array1's taggedFileId with the array2's taggedFileId and if found then insert a array2's rateResult in array1's found index.

The result should be as follows

`

array1 = [
   {
     _id: new ObjectId("639979460a52134240478a9b"),
     taggedFileId: '6399798f0a52134240478abf',
     rateResult: 'none',
   },
   {
     _id: new ObjectId("639b576c2743a77ea2812f07"),
     taggedFileId: '639988250a52134240478b07'
     rateResult: 'none',
   }
 ]

`

CodePudding user response:

use this code:

array2.forEach(item => {
    const foundIndex = array1.findIndex(i => i.taggedFileId === item.taggedFileId);
    if(foundIndex >= 0){
       array1[foundIndex].rateResult =  item.rateResult;
    }
})

CodePudding user response:

You can use Array.find to find the item in array2 with the same rateResult property value:

function ObjectId(){}

array1=[{_id:new ObjectId("639979460a52134240478a9b"),taggedFileId:"6399798f0a52134240478abf"},{_id:new ObjectId("639b576c2743a77ea2812f07"),taggedFileId:"639988250a52134240478b07"}],array2=[{fileIds:new ObjectId("639979460a52134240478a9b"),rateResult:"none",taggedFileId:"6399798f0a52134240478abf",_id:new ObjectId("639c8531dcd57c7d559e6211")},{fileIds:new ObjectId("639b576c2743a77ea2812f07"),rateResult:"none",taggedFileId:"639988250a52134240478b07",_id:new ObjectId("639c8531dcd57c7d559e6212")}];

array1.forEach(({ taggedFileId }, i) => {
  const itm = array2.find(e => e.taggedFileId == taggedFileId)
  if(itm) array1[i].rateResult = itm.rateResult
})

console.log(array1)

  • Related