我想组合两个包含json对象的数组,但是通过在键前添加一些文本来保留重复键。在下面的示例中,来自对象json2的数据覆盖了对象json1,因为它们具有相同的键,但我也希望保留第一个对象的数据。感谢。
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));
正在返回
[
{
"Column1": "json2",
"Column2": "json2",
},
{
"Column1": "json2",
"Column2": "json2",
}
];
但我想要
[
{
"json1Column1": "json1",
"json1Column2": "json1",
"json2Column1": "json2",
"json2Column2": "json2",
},
{
"json1Column1": "json1",
"json1Column2": "json1",
"json2Column1": "json2",
"json2Column2": "json2",
}
];
答案 0 :(得分:2)
我唯一能想到的是创建一个向对象添加前缀的函数:
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;
}
之后避免使用angular.extend,它不支持深度属性复制。这就是为什么第二个对象的属性被复制到第一个对象的原因。你需要的是angular.merge,所以你的代码将在实现上一个函数之后:
var nJson1=addPrefix(json1,"json1");
var nJson2=addPrefix(json2,"json2");
var merged = angular.merge({},nJson1,nJson2);
答案 1 :(得分:1)
一些提案,其中包含对密钥和项目的迭代。
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>');
&#13;