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

JavascriptWeb DevelopmentObject Oriented Programming

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 } }
]
raja
Published on 14-Sep-2020 10:09:00
Advertisements