0

How can I add the status property from object1 into object2 based on employeeId matching id?

var object1 = [ 
    { status: 'Complete', employeeId: 1 },
    { status: 'Updating', employeeId: 2 },
    { status: 'Finished', employeeId: 3 }
];

var object2 = [ 
    { name: 'Ben', Id: 1 },
    { name: 'Jim', Id: 2 },
    { name: 'Dan', Id: 3 }
];
noclist
  • 1,659
  • 2
  • 25
  • 66
  • 1
    Does this answer your question? [Merge two array of objects based on a key](https://stackoverflow.com/questions/46849286/merge-two-array-of-objects-based-on-a-key) – VLAZ Jan 30 '23 at 16:59
  • Potentially, could you give me an example just based on my arrays? The results in that post are a bit over my head. – noclist Jan 30 '23 at 17:03
  • [this answer](https://stackoverflow.com/a/51672402/) with `arr1 = object1`, `arr2 = object`, change `item.id === itm.id` to `item.Id === itm.employeeId` – VLAZ Jan 30 '23 at 17:10

1 Answers1

1
var object1 = [ 
    { status: 'Complete', employeeId: 1 },
    { status: 'Updating', employeeId: 2 },
    { status: 'Finished', employeeId: 3 }
];

var object2 = [ 
    { name: 'Ben', Id: 1 },
    { name: 'Jim', Id: 2 },
    { name: 'Dan', Id: 3 }
];

for(let i = 0; i < object2.length; i++) { // for each object2  
  // find the matching object1
  const matchedObj1 = object1.find((obj1) => obj1.employeeId === object2[i].Id)
  // if found successfully
  if (matchedObj1 !== undefined)
  {  
    // recreate object2, with it's original properties plus the matchedObj1 status property
    object2[i] = {...object2[i], ...{ status: matchedObj1.status } }   
  }
}
Stewart
  • 705
  • 3
  • 6