Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/Replace object from array of objects JavaScript

I want to Add/Replace the object from array of objects by testing some properties against array object

  • Replace object if name and id matches

  • Add object to the array if name and id does not match from array objects

I am using below code, its working fine but I am not sure is it a good solution.

let arr = [{name: 'test1', id:1, data: {a:1} }, {name:'test2', id:2, data: {a:2}}]
let obj = {name:'test3', id:3, data: {a:3}}
let itemFound = false;
let newArr = arr.map((item)=>{
  let test = item.name === obj.name && item.id === obj.id;
  if(test){
	itemFound = true;
  }
  return test ? obj : item;
});

if(!itemFound){
	newArr.push(obj);
}
console.log(newArr)
like image 610
Dipak Telangre Avatar asked Feb 12 '18 09:02

Dipak Telangre


People also ask

How do you add an object to an existing array?

The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the beginning of the array.

Can we convert array to object in JavaScript?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied!


Video Answer


1 Answers

You could look for the index and update the array, if found or push the object.

var array = [{ name: 'test1', id: 1, data: { a: 1 } }, { name: 'test2', id: 2, data: { a: 2 } }],
    object = { name: 'test3', id: 3, data: { a: 3 } },
    index = array.findIndex(({ name, id }) => name === object.name && id === object.id);

if (index === -1) {
    array.push(object);
} else {
    array[index] = object;
}

console.log(array);
like image 191
Nina Scholz Avatar answered Oct 04 '22 19:10

Nina Scholz