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
See Question&Answers more detail:
os