user1184100
user1184100

Reputation: 6894

Merging objects of an array using lodash

I'm trying to merge all objects together using lodash and I tried _.assign and _.merge still it shows the objects separately.

 var arr = [
    {"asf" : 33, "ff1" : 12},{"xx" : 90, "ff2" : 13},{"xw" : 66, "ff3" : 176}
]
  console.log( _.assign({}, arr)); //should show {"asf" : 33, "ff1" : 12,"xx" : 90, "ff2" : 13, "xw" : 66, "ff3" : 176}

http://jsfiddle.net/ymppagdq/

Upvotes: 7

Views: 14730

Answers (3)

caseyWebb
caseyWebb

Reputation: 2086

In ES2015, you can use _.assign(...arr), or if you're really only targeting ES2015, Object.assign(...arr).

Upvotes: 9

dfsq
dfsq

Reputation: 193261

This is how you can do it:

_.assign.apply(_, arr);

Demo: http://jsfiddle.net/ymppagdq/2/

or _.reduce(arr, _.extend) would also work.

Upvotes: 16

Douglas
Douglas

Reputation: 37763

If there isn't a method which accepts an array of objects, apply can be used to call with multiple arguments:

var arr = [...];
_.assign.apply(_, [{}].concat(arr))

Upvotes: 0

Related Questions