vinesh
vinesh

Reputation: 4913

Merge objects containing array

How can I merge two objects containing array and other fields using lodash?

For example,

obj1 = {
    name: "abc",
    hobbies: ["reading","cricket"]
}
obj2 = {
    name: "abc2",
    hobbies: ["reading","hockey"]
}
_.merge(obj1, obj2)

// output
{
    name: "abc2",
    hobbies: ["reading","hockey"]
}

this returns an object after merging obj1 into obj2 but without merging the hobbies.

Upvotes: 1

Views: 69

Answers (1)

Bart Jedrocha
Bart Jedrocha

Reputation: 11570

Underscore.js doesn't have a _.merge function so I'm assuming you're using Lo-Dash. If that's the case, you can use the callback parameter to do what you want

var obj1 = { name: 'abc', hobbies: ['reading', 'cricket'] };
var obj2 = { name: 'def', hobbies: ['reading', 'hockey'] };

var output = _.merge(obj1, obj2, function(a,b) {
    return _.isArray(a) ? _.union(a,b) : undefined;
} );
console.log( output );

// output

{ name: 'def', hobbies: ['reading', 'cricket', 'hockey'] }

EDIT

Working JSFiddle.

Upvotes: 3

Related Questions