简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM