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 }
];
CodePudding user response:
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 } }
}
}