Ram Mohan Reddy
Ram Mohan Reddy

Reputation: 11

Merging two arrays of objects with different keys/properties

array1 = [{
        id: "David Moorman",
        current - margin: "500",
        current - customers: 123
    },
    {
        id: "Elaina Wasmus",
        current - margin: "600",
        current - customers: 45
    }
];
array2 = [{
    name: "Jose Maldonado",
    Purposed - margin: "700",
    purposed - customers: 100
}, {
    name: "David Moorman",
    Purposed - margin: "1000",
    purposed - customers: 34
}];

This is output array:

merge array = [{
    id: "David Moorman",
    current - margin: "500",
    Purposed - margin: "1000",
    current - customers: 123,
    purposed - customers: 100
}, {
    id: "Elaina Wasmus",
    current - margin: "600",
    Purposed - margin: NULL,
    current - customers: 45,
    purposed - customers: null
}, {
    id: "Jose Maldonado",
    current - margin: "0",
    Purposed - margin: "700",
    current - customers: null,
    purposed - customers: 100
}];

Upvotes: 0

Views: 177

Answers (2)

Sagar Chaudhary
Sagar Chaudhary

Reputation: 1403

You can use lodash for this.
Here I am taking the name field in array2 as the id field.

 finalArr = _(_.flatten([array1, array2]))
                                        .groupBy('id')
                                        .map(_.spread(_.assign))
                                        .value();

This will work only if the array2 has id field with values of name field.
Both array must have a unique field so as to merge properly.

Upvotes: 2

dRoyson
dRoyson

Reputation: 1507

From what I understand, this would be my implementation using lodash:

var finalArray = _.zipWith(array1, array2, function(a,b){
  return _.merge(a,b);
})

Check lodash docs here: https://lodash.com/docs/4.17.10

Upvotes: 1

Related Questions