skip to Main Content

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


  1. Use Array::map() to get a copy of the array with the replaced value:

    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};
    
    console.log(oldEmployees.map(old => newEmployee.id === old.id ? newEmployee : old));
    Login or Signup to reply.
  2. If ids are unique, a better way is to store them in a Map or a object with ids as key.

    /*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ 
    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 };
    const oldEmployeesMap = oldEmployees.reduce(
      (a, c) => a.set(c.id, c),
      new Map()
    );
    oldEmployeesMap.set(newEmployee.id, newEmployee);
    console.log([...oldEmployeesMap.values()]);
    <!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search