Skip to content
Advertisement

Compare and add property to array of object

I have two arrays of objects (Obj1 and Obj2).

The difference is that Obj2 objects have an extra property called fn. I want to compare both arrays and if an object in Obj1 has fn in Obj2 for the same datakey then want to add fn in Obj1 also (the datakey is unique).

I don’t want to change the order of Obj1 array and I don’t want to remove any extra object from Obj1.

I tried the following but, it doesn’t seem to work or I am doing the wrong way.

JavaScript

Expected Output:

JavaScript

Advertisement

Answer

Just iterate Obj2 and use Array.find() to find the corresponding value on Obj1

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement