Concatenate two arrays of objects and remove repeated data from an attribute in JavaScript?


For this, use map() along with find(). Following is the code −

Example

var details1 =
[
   {
      productDetails:
      {
         isSold: true,
         productId:101
      }
   },
   {
      productDetails:
      {
         isSold: true,
         productId:103
      }
   }
]
var details2 =
[
   {
      productDetails:
      {
         isSold: false,
         productId:101
      }
   }
]
var details3 = details1.map(details1Object=>{
   var newObject= details2.find(obj=>obj.productDetails.productId
   === details1Object.productDetails.productId)
   return newObject? newObject : details1Object
})
console.log(details3)

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

node fileName.js.

Here, my file name is demo183.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo183.js
[
   { productDetails: { isSold: false, productId: 101 } },
   { productDetails: { isSold: true, productId: 103 } }
]

Updated on: 14-Sep-2020

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements