I would like to efficiently replace an object in an array with another object based on a property of that object in JavaScript. Here is an example below:
const oldEmployees = [
{id: 1, name: 'Jon', age: 38},
{id: 2, name: 'Mike', age: 35},
{id: 3, name: 'Shawn', age: 40}
];
const newEmployee = {id: 2, name: 'Raj', age: 32};
I would like the output to be:
[
{id: 1, name: 'Jon', age: 38},
{id: 2, name: 'Raj', age: 32},
{id: 3, name: 'Shawn', age: 40}
]
What would be the most efficient method to do this?
2
Answers
Use
Array::map()
to get a copy of the array with the replaced value:If ids are unique, a better way is to store them in a Map or a object with ids as key.