Having the following array of objects:
const input = [ {id: 3, data: {name: 'john'} },
{id: 6, data: {name: 'mike'} },
{id: 2, data: {name: 'anna'} }
];
I want to write a method that recevies a new object, if the object’s id is in the array, it replaces that one with the new one, otherwise it creates a new object.
For example, if the method receives this object: {id: 1, data: {name: 'maria' }}
, it will add it to the array, so the array will look like:
const input = [ {id: 3, data: {name: 'john'} },
{id: 6, data: {name: 'mike'} },
{id: 2, data: {name: 'anna'} },
{id: 2, data: {name: 'maria'} }
];
If it receives {id: 3, data: {name: 'jack' }}
it should replace the object with id=3 so the result would be:
const input = [ {id: 3, data: {name: 'jack'} },
{id: 6, data: {name: 'mike'} },
{id: 2, data: {name: 'anna'} },
{id: 2, data: {name: 'maria'} }
];
The code:
function doMagic(input, newObj) {
if (input.some(el => el.id === newObj.id) {
// replace it
} else {
// add the object to the array
}
}