javascript - Merge two array of objects with same keys, some object won't have the same value? - Stack Overflow

I want to merge two arrays of objects. The keys are the same but the values might not always be the same

I want to merge two arrays of objects. The keys are the same but the values might not always be the same.

Any solution is appreciated preferably in javascript, but a python solution is fine as well.

Here is the sample data:

var g= [ 
    { id: 36, name: 'AAA', goal: 'yes' , 'random':27},
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 39, name: 'JJJ', goal: 'yes' },
    { id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}];


var c= [ 
    { id: 36, name: 'AAA', goal: 'yes', color:"purple" },
    { id: 40, name: 'BBB', circle: 'yes', color:"purple" },
    { id: 100, name: 'JJJ', circle: 'yes'} ];

My expected output should be :

 var finalData = [{
 { id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"},
 { id: 40, name: 'BBB', circle: 'yes', color:"purple"},
 { id: 39, name: 'JJJ', goal: 'yes' },
 { id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"},
 { id: 100, name: 'JJJ', circle: 'yes' }

  }]

Here is my current code, it works to some degree but it doesn't add keys it might have missed.

var finalData = [];
for(var i in g){
   var shared = false;
   for (var j in c)
       if (c[j].name == g[i].name) {
           shared = true;
           break;
       }
   if(!shared) finalData.push(g[i])
}
finalData = finalData.concat(c); 

finalData

I want to merge two arrays of objects. The keys are the same but the values might not always be the same.

Any solution is appreciated preferably in javascript, but a python solution is fine as well.

Here is the sample data:

var g= [ 
    { id: 36, name: 'AAA', goal: 'yes' , 'random':27},
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 39, name: 'JJJ', goal: 'yes' },
    { id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}];


var c= [ 
    { id: 36, name: 'AAA', goal: 'yes', color:"purple" },
    { id: 40, name: 'BBB', circle: 'yes', color:"purple" },
    { id: 100, name: 'JJJ', circle: 'yes'} ];

My expected output should be :

 var finalData = [{
 { id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"},
 { id: 40, name: 'BBB', circle: 'yes', color:"purple"},
 { id: 39, name: 'JJJ', goal: 'yes' },
 { id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"},
 { id: 100, name: 'JJJ', circle: 'yes' }

  }]

Here is my current code, it works to some degree but it doesn't add keys it might have missed.

var finalData = [];
for(var i in g){
   var shared = false;
   for (var j in c)
       if (c[j].name == g[i].name) {
           shared = true;
           break;
       }
   if(!shared) finalData.push(g[i])
}
finalData = finalData.concat(c); 

finalData
Share Improve this question edited Mar 4, 2018 at 16:35 str 45.1k18 gold badges114 silver badges134 bronze badges asked Dec 8, 2017 at 11:38 SayranSayran 1631 gold badge2 silver badges11 bronze badges 2
  • What is there both has the same key say goal? – Nishant Commented Dec 8, 2017 at 11:45
  • Possible duplicate of Merge 2 arrays of objects – Nishant Commented Dec 8, 2017 at 11:48
Add a ment  | 

3 Answers 3

Reset to default 4

You could use a Map for keeping same id in the same object and Object.assign for creating independent objects.

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    map = new Map,
    result = g.concat(c).reduce(function (r, o) {
        var temp;
        if (map.has(o.id)) {
            Object.assign(map.get(o.id), o);
        } else {
            temp = Object.assign({}, o);
            map.set(temp.id, temp);
            r.push(temp);
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Version without reduce and without concat.

function merge(o) {
    var temp;
    if (map.has(o.id)) {
        Object.assign(map.get(o.id), o);
        return;
    }
    temp = Object.assign({}, o);
    map.set(temp.id, temp);
    result.push(temp);
}

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    map = new Map,
    result = [];

[g, c].forEach(function (a) {
    a.forEach(merge);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

With dynamic key.

function mergeBy(key, data) {
    return Array.from(data
        .reduce((m, o) => m.set(o[key], { ...m.get(o[key]), ...o }), new Map)
        .values()
    );
}

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    result = mergeBy('id', [...g, ...c]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Here's a Python solution. This modifies g, which you may or may not want.

c_by_id = {d['id']: d for d in c}
for item in g:
    item.update(c_by_id.get(item['id']), {})

This can be easily achieved by underscore functions _.uniq and _.union.

Just use this:

var finalData = _.uniq(_.union(c, g),  function (ele)  {
                    return ele.id
                })

This will return you what you are looking for.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745173515a4615070.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信