Tulun Tulun - 1 month ago 9
Javascript Question

Merge 2 sorted array of objects using lodash by their properties

I am trying to merge two arrays of objects together.

I have presorted the arrays of objects so that they match, I just need to push the properties across each object in both arrays.

I think lodash would give me a cleaner solution than a double for loop, or should I just do a vanilla JS solution?

Example of two arrays:

[
{
provider: 'foo',
title: 'Title1'
},
{
provider: 'bar',
title: 'Title2'
}
]

[
{
all: '0',
novelty: '24'
},
{
all: '4',
novelty: '12'
}
]


It should return:

[
{
provider: 'foo',
title: 'Title1',
all: '0',
novelty: '24'
},
{
provider: 'bar',
title: 'Title2',
all: '4',
novelty: '12'
}
]

Answer

Without lodash you can use Array.prototype.map() and Object.assign() (or angular.merge() if assign is not supported by the target browsers):

var arr1 = [{
      provider: 'foo',
      title: 'Title1'
    }, {
      provider: 'bar',
      title: 'Title2'
    }];

    var arr2 = [{
      all: '0',
      novelty: '24'
    }, {
      all: '4',
      novelty: '12'
    }];

    var result = arr1.map(function(item, index) {
      return Object.assign({}, item, arr2[index]);
    });

    console.log(result);

If you want to use lodash use _.zipWith() with _.assign():

var arr1 = [{
  provider: 'foo',
  title: 'Title1'
}, {
  provider: 'bar',
  title: 'Title2'
}];

var arr2 = [{
  all: '0',
  novelty: '24'
}, {
  all: '4',
  novelty: '12'
}];

var result = _.zipWith(arr1, arr2, function(a, b) {
  return _.assign({}, a, b);
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>