Reputation: 45
I want to combine two arrays containing json objects but keep the duplicate keys by prepending the keys with some text. In the example below the data from the object json2 is overwriting the object json1 because they have the same keys but I want to keep the data from the 1st object as well. Thanks.
var json1 = [
{
"Column1": "json1",
"Column2": "json1",
},
{
"Column1": "json1",
"Column2": "json1",
}
];
var json2 = [
{
"Column1": "json2",
"Column2": "json2",
},
{
"Column1": "json2",
"Column2": "json2",
}
];
console.log(angular.extend(json1, json2));
is returning
[
{
"Column1": "json2",
"Column2": "json2",
},
{
"Column1": "json2",
"Column2": "json2",
}
];
but I want
[
{
"json1Column1": "json1",
"json1Column2": "json1",
"json2Column1": "json2",
"json2Column2": "json2",
},
{
"json1Column1": "json1",
"json1Column2": "json1",
"json2Column1": "json2",
"json2Column2": "json2",
}
];
Upvotes: 1
Views: 1248
Reputation: 836
The only thing I can think is to create a function to add prefix to objects:
function addPrefix(target, prefix){
var newObj = false;
if(target.constructor === Array){
newObj = [];
for(var i = 0 ; i< target.length; i++){
item = target[i];
var itemObj = {};
for(var key in item){
itemObj[prefix+key] = item[key];
}
newObj.push(itemObj);
}
}else{
newObj = {};
for(var key in target){
newObj[prefix+key] = target[key];
}
}
return newObj;
}
After that avoid using angular.extend, it doesn't support deep properties copy. So that's the reason why the properties from the second object are copied into the first. What you need is angular.merge, so you code would be after implementing the previous function:
var nJson1=addPrefix(json1,"json1");
var nJson2=addPrefix(json2,"json2");
var merged = angular.merge({},nJson1,nJson2);
Upvotes: 2
Reputation: 386604
A proposal with some iterating over the keys and over the items.
var obj1 = [{ Column1: "json11", Column2: "json11", }, { Column1: "json12", Column2: "json12", }],
obj2 = [{ Column1: "json21", Column2: "json21", }, { Column1: "json22", Column2: "json22", }],
result = function (data) {
var r = [];
Object.keys(data).forEach(function (k) {
data[k].forEach(function (a, i) {
r[i] = r[i] || {};
Object.keys(a).forEach(function (l) {
r[i][k + l] = a[l];
});
});
});
return r;
}({ json1: obj1, json2: obj2 });
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Upvotes: 1