How to add a new object into a JavaScript array after map and check condition?


For this, you can use filter() along with map().

Example

const details =[
   { customerName: 'John', customerCountryName: 'UK', isMarried :true },
   { customerName: 'David', customerCountryName: 'AUS', isMarried :false },
   { customerName: 'Mike', customerCountryName: 'US', isMarried :false }
]
let tempObject = details.filter(obj=> obj.isMarried == true);
tempObject["customerNameWithIsMarriedFalse"] = details.filter(obj =>
obj.isMarried== false).map(obj => obj.customerName);
console.log(tempObject);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo176.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo176.js
[
   { customerName: 'John', customerCountryName: 'UK', isMarried: true }, customerNameWithIsMarriedFalse: [ 'David', 'Mike' ]
]

Updated on: 12-Sep-2020

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements