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' }
]

Updated on: 03-Oct-2020

818 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements