Sahas
Sahas

Reputation: 3186

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');
var one = [{
  id:1
},
{
  id:2
}];
var two = [{
  id:2,
  name:"test1"
},
{
  id:1,
  name:"test2"
}];

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

deepmerge results in blind merge, first element with first element from the other array.

[ { id: 2, name: 'test1' }, { id: 1, name: 'test2' } ]

I know its possible to manually iterate thru one array, find the matching node from the other array and merge them...wondering if there is any library to do this. Thoughts?

Upvotes: 2

Views: 3067

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

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

function merge(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);

Upvotes: 3

Anirudha
Anirudha

Reputation: 32797

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 }] }

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

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));

Upvotes: 0

Related Questions