1

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.

5
  • So, you want to overwrite name with obj2, but not overwrite hobbies? Commented Jan 7, 2015 at 20:17
  • I want hobbies to be merged(union). Commented Jan 7, 2015 at 20:21
  • Your output is just the same as obj2. I'm a little confused at the result you want. Commented Jan 7, 2015 at 20:23
  • Name is correct. I want hobbies to be reading, cricket, hockey Commented Jan 7, 2015 at 20:25
  • _.merge isn't part of underscore.js. Where are you getting that from? Commented Jan 7, 2015 at 20:31

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.