- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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