0

I have two arrays of objects:

array1 = [{id : 1, pop: 4000}, etc.]
array2 = [{id : 1, size: 2000}, etc.]

I would like to merge the two arrays (on id) for:

merged = [{id :1, pop: 4000, size: 2000}, etc.]

I saw extend and other options like concat but nothing quite what I was going for

As3adTintin
  • 2,406
  • 12
  • 33
  • 59

5 Answers5

0

No need for underscore, you can use Object.assign:

Working Example

var array1 = [{id : 1, pop: 4000}, {id : 2, pop: 4000}];

var array2 = [{id : 1, size: 2000}, {id : 1, blah: 4000}, {id : 2, size: 4000}];

var merged = [];

for (var i = 0; i < array1.length; i++) {
  var obj = {};
   for (var j = 0; j < array2.length; j++) {
     if (array1[i].id === array2[j].id) {
       obj = Object.assign(obj, array1[i], array2[j]);
       merged.push(obj);
     }
   }
}
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

With lodash:

result = _(array1)
     .concat(array2)
     .groupBy('id')
     .map(_.spread(_.extend))
     .value();

Unlike map+find solutions, this is linear. Note that it's a "full outer" join, so the result will include non-matching elements from both arrays.

georg
  • 211,518
  • 52
  • 313
  • 390
0

Using underscore JS :

var array1 = [{ id: 1, pop: 4000 }, { id: 2, pop: 7000 }];

  var array2 = [{ id: 1, pop: 5000 }, { id: 2, pop: 6000 }];

var merge = _.map(array1, function(curr){

    return _.extend(curr, _.findWhere(array2, { id: curr.id })); });

I think it should work..

Sahar Ben-Shushan
  • 297
  • 1
  • 3
  • 20
0

A solution in plain Javascript with Array#forEach and Object.keys and an object for the reference to the array elements.

var array1 = [{ id: 1, pop: 4000 }, { id: 2, pop: 2000 }],
    array2 = [{ id: 1, size: 2000 }, { id: 2, size: 0 }],
    merged = [];

function getMerged(array1, array2) {
    function iter(a) {
        if (!obj[a.id]) {
            obj[a.id] = { id: a.id };
            result.push(obj[a.id]);
        }
        Object.keys(a).forEach(function (k) {
            if (k !== 'id') {
                obj[a.id][k] = a[k];
            }
        });
    }

    var result = [],
        obj = Object.create(null);

    array1.forEach(iter);
    array2.forEach(iter);
    return result;
}

console.log(getMerged(array1, array2));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use _.map, _.extend and _.findWhere in Underscore.

Example:

const array1 = [{
  "id": 1,
  "pop": 400
}, {
  "id": 2,
  "pop": 2000
}];
const array2 = [{
  "id": 1,
  "size": 5000
}, {
  "id": 2,
  "size": 500
}];


const mergeById = (a, b) => a.map(x => _.extend(x, _.findWhere(b, {"id": x.id})));

console.log(mergeById(array1, array2));

/* RESULT:

 [
  {
    "id": 1,
    "pop": 400,
    "size": 5000
  },
  {
    "id": 2,
    "pop": 2000,
    "size": 500
  }
]
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Aral Roca
  • 5,442
  • 8
  • 47
  • 78