How do I merge an array of objects in Javascript?

前端 未结 3 1698
我寻月下人不归
我寻月下人不归 2020-12-20 23:19

Example:

var array1 = [ {\'key\':1, \'property1\': \'x\'}, {\'key\':2, \'property1\': \'y\'} ]
var array2 = [ {\'key\':2, \'property2\': \'a\'}, {\'key\':1,          


        
3条回答
  •  庸人自扰
    2020-12-20 23:51

    It would be preferable to use existing infrastructure such as Underscore's _.groupBy and _.extend to handle cases like this, rather than re-inventing the wheel.

    function merge(array1, array2) {
    
      // merge the arrays
      // [ {'key':1, 'property1': 'x'}, {'key':2, 'property1': 'y'}, {'key':2, 'property2': 'a'}, {'key':1, 'property2': 'b'} ]
      var merged_array = array1.concat(array2);
    
      // Use _.groupBy to create an object indexed by key of relevant array entries
      // {1: [{ }, { }], 2: [{ }, { }]}
      var keyed_objects = _.groupBy(merged_array, 'key');
    
      // for each entry in keyed_objects, merge objects
      return Object.keys(keyed_objects).map(function(key) {
        return _.extend.apply({}, keyed_objects[key]);
      });
    
    }
    

    The idea here is using _.extend.apply to pass the array of objects grouped under a particular key as arguments to _.extend, which will merge them all into a single object.

提交回复
热议问题