Home > Software engineering >  How to find and replace an object with in array of objects
How to find and replace an object with in array of objects

Time:02-18

I have an array of objects like this.

 [{
    "id": 1,
    "name": "January",
    "abc": abc,
    "xyz": xyz
}, {
    "id": 2,
    "name": "February",
    "abc": abc,
    "xyz": xyz
}]

I want to replace the object which is having id 2 with the different object and i want to have my object like this .

 [{
    "id": 1,
    "name": "January",
    "abc": abc,
    "xyz": xyz
}, {
    "id": 2,
    "name": "New month",
    "abc": 1234abc,
    "xyz": someVlaue
}]

how to do it in efficient way in typescript or javascript.

CodePudding user response:

Looks like this was explained well in this post. The top answer explained how to use find(), as well as findIndex(). Should help you achieve what you are looking to do.

Find object by id in an array of JavaScript objects

EDIT: Forgot about the replacement piece.

Replace a particular object based on id in an array of objects in javascript

CodePudding user response:

const arr =  [{
  "id": 1,
  "name": "January",
  "abc": "abc",
  "xyz": "xyz"
}, {
  "id": 2,
  "name": "February",
  "abc": "abc",
  "xyz": "xyz"
}]

const index = arr.findIndex(entry => entry.id === 2);
arr[index] = {id: 2, name: "New month", abc: "1234abc", xyz: "someVlaue"} // (sic)

CodePudding user response:

You can use Object.assign() with find() as follows:

const data = [{
    "id": 1,
    "name": "January",
    "abc": "abc",
    "xyz": "xyz"
}, {
    "id": 2,
    "name": "February",
    "abc": "abc",
    "xyz": "xyz"
}];

Object.assign(
    //find the desired object
    data.find(({id,name,abc,xyz}) => id === 2),
    //pass these new values 
    {name:"New Month",abc:"abc123",xyz:"someValue"}
);

console.log( data );

  • Related