
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Object to Array in JavaScript if Name Does Not Already Exist
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' } ]
Advertisements