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.
Different ways to achieve this.
const data = [{
"id": 1,
"name": "January",
"abc": "abc",
"xyz": "xyz"
}, {
"id": 2,
"name": "February",
"abc": "abc",
"xyz": "xyz"
}];
const target = data.find((obj) => obj.id === 2);
const source = {
id: 2,
name: 'New Month',
abc: 'abc123',
xyz: 'someValue'
};
Object.assign(target, source);
console.log( data );
const data = [{"id": 1,"name": "January","abc": "abc","xyz": "xyz"}, {"id": 2,"name": "February","abc": "abc","xyz": "xyz"}];
const modifiedObj = {"id": 2,"name": "New month","abc": "1234abc","xyz": "someVlaue"};
const result = data.map((item) => item.id === modifiedObj.id ? modifiedObj : item);
console.log(result);
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
Another way to replace the object:
const data = [{"id": 1,"name": "January","abc": "abc","xyz": "xyz"}, {"id": 2,"name": "February","abc": "abc","xyz": "xyz"}];
const newObj = {"id": 2,"name": "New month","abc": "1234abc","xyz": "someVlaue"};
const targetId = 2;
const result = data.map((obj) => obj.id === targetId ? newObj : obj);
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}