0

Consider values as an undetermined list of objects.

I want an effective ES5 version of this:

var result = _.merge({}, ...values); // <-- This is what I want

Since ...anything is not allowed I've made this:

var result _.reduce(response, function(result, value) {
  return _.merge(result, value);
}, {});

But I'm pretty sure it's not the best way to do ...

Any ideas ?

HollyPony
  • 817
  • 9
  • 15
  • 1
    If `values` is an array then I think you can just use `_.merge({}, values)`. Alternatively your example can be simplified to `_.reduce(response, _.merge, {})`. – Gruff Bunny Jan 04 '17 at 12:21
  • `_.merge({}, values)` will result to put values `in` instead of `with` the `{}` . `_.reduce(response, _.merge, {})` is a good point ;) . But I think it is no more efficient. – HollyPony Jan 04 '17 at 12:41
  • One less function call for each value but that is a piddly amount of time :) – Gruff Bunny Jan 04 '17 at 13:07

1 Answers1

1

You can use use Function#apply on the array of values. You need to Array#concat an empty object if you don't want to mutate the original objects:

_.merge.apply(_, [{}].concat(arr));

Example:

var arr = [{ a: 1 }, { b: 2 }, { c: 3 }];

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

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209