Add object to array in JavaScript if name does not already exist?

JavascriptWeb DevelopmentObject Oriented Programming

For this, use push() along with forEach(). Following is the code −

Example

var details = [{name:"John"},{name:"David"}]
var addObject = ["Mike","Sam"];
addObject.forEach( obj1 => {
   if(!details.find( obj2 => obj2===obj1 ))
      details.push({name:obj1})
})
console.log(details);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo165.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo165.js
[
   { name: 'John' },
   { name: 'David' },
   { name: 'Mike' },
   { name: 'Sam' }
]
raja
Published on 12-Sep-2020 08:12:13
Advertisements