- 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 property to common items in array and array of objects - JavaScript?
To add property, use map(). Let’s say the following is our array −
const firstname = ['John', 'David', 'Bob'];
Following are our array of objects −
const studentDetails = [ { firstname: 'Carol', marks: 78 }, { firstname: 'Mike', marks: 89 }, { firstname: 'Bob', marks: 86 } ];
Example
Following is the code −
const firstname = ['John', 'David', 'Bob']; const studentDetails = [ { firstname: 'Carol', marks: 78 }, { firstname: 'Mike', marks: 89 }, { firstname: 'Bob', marks: 86 } ]; const data = new Set(firstname); const result = studentDetails.map(tmpObject => { if (data.has(tmpObject.firstname)) tmpObject.isPresent ="This is present"; else tmpObject.isPresent = "This is not present"; return tmpObject; }); console.log(result);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo219.js.
Output
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo219.js [ { firstname: 'Carol', marks: 78, isPresent: 'This is not present' }, { firstname: 'Mike', marks: 89, isPresent: 'This is not present' }, { firstname: 'Bob', marks: 86, isPresent: 'This is present' } ]
Advertisements