javascriptlodashes5-shim

Optimization - Compatibility for lodash merge with many args


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 ?


Solution

  • 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>