- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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' } ]
- Related Articles
- Comparing objects in JavaScript and return array of common keys having common values
- Sum of array object property values in new array of objects in JavaScript
- Add values of matching keys in array of objects - JavaScript
- Array of objects to array of arrays in JavaScript
- Filter array of objects by a specific property in JavaScript?
- Retrieve property value selectively from array of objects in JavaScript
- Sort array of objects by string property value in JavaScript
- Sorting an array of objects by property values - JavaScript
- Sort array of objects by string property value - JavaScript
- Remove property for all objects in array in JavaScript?
- How to iterate over objects in array and sum a property in JavaScript
- Sort array according to the date property of the objects JavaScript
- Search from an array of objects via array of string to get array of objects in JavaScript
- Manipulating objects in array of objects in JavaScript
- How to convert array into array of objects using map() and reduce() in JavaScript

Advertisements