Skip to content Skip to sidebar Skip to footer

Merge 2 Json Array Objects Based On A Common Property

I got 2 Json arrays with some common field. But they are not sorted in any specific order. I want to be able to merge them based on a property. var merge = require('deepmerge'); va

Solution 1:

You could use a function and define the common key, on which the merging should group. It works with unsorted data.

functionmerge(arrays, key) {
    var r = [],
        hash = Object.create(null);

    arrays.forEach(function (a) {
        a.forEach(function (o) {
            if (!hash[o[key]]) {
                hash[o[key]] = {};
                r.push(hash[o[key]]);
            }
            Object.keys(o).forEach(function (k) {
                hash[o[key]][k] = o[k];
            });
        });
    });
    return r;
}

var one = [{ id: 1, score: 100 }, { id: 2, score: 200 }, { id: 4, score: 400 }],
    two = [{ id: 2, name: "test1" }, { id: 1, name: "test2" }, { id: 3, name: "test3" }],
    merged = merge([one, two], 'id');

console.log(merged);

Solution 2:

Sort both arrays before hand?

one.sort((a, b) => a.id - b.id);
two.sort((a, b) => a.id - b.id);

Now that the arrays are sorted you should be able to merge them properly:

console.log(merge(one, two));

Solution 3:

I think you are looking for merge in lodash. Subsequent sources overwrite property assignments of previous sources. So this will overwrite the subsequent id's

var users = {
  'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
};

var ages = {
  'data': [{ 'age': 36 }, { 'age': 40 }]
};

_.merge(users, ages);
// → { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }

Post a Comment for "Merge 2 Json Array Objects Based On A Common Property"