我有一个看起来像这样的对象:
var obj = {
1: {
'x': [ [], [], [] ],
'y': [ [], [] ],
},
2: {
'x': [ [], [] ],
'z': [ [] ],
},
}
我还有另一个对象,我希望得到差异并加入其中。
var newObj = {};
我想将此对象与另一个对象进行比较,并获得差异。我只想评估'整数'键级和'字母'键级别,而不是内部子级。
根据差异,添加缺失的并删除已删除的。但是,在做这种差异时,我想只添加新的键和值,如下所示:'new': [ [] ]
,但如果它们存在且不接触它们,请保留现有的键和值。只添加空数组值的缺失键。
有办法吗?
这是一个小提琴,我用例子详细解释了: https://jsfiddle.net/7ccd3una/1/
如果:
var newObj = {
1: {
'x': [ [], [], [] ],
},
2: {
'z': [ [] ],
},
}
和obj是
var obj = {
1: {
'x': [ [], [], [] ],
'y': [ [], [] ],
},
2: {
'x': [ [], [] ],
'z': [ [] ],
},
}
在函数调用之后,我希望newObj是这样的(只为新的数组添加一个空数组):
newObj = {
1: {
'x': [ [], [], [] ],
'y': [ [] ]
},
2: {
'x': [ [] ],
'z': [ [] ],
},
}
完整示例:
newObj = {} // just initialised.
obj = {
1: {
'x': [ [], [], [] ],
'y': [ [] ]
},
}
// newObj becomes,
newObj : {
1: {
'x': [ [] ],
'y': [ [] ]
},
}
// This newObj can get structured itself. So it can become like:
newObj : {
1: {
'x': [ [], [], [] ],
'y': [ [] ]
},
}
// ..separately from the obj.
// So I want to watch the letter key adds and removes actually. Let's say obj became:
obj : {
1: {
'x': [ [] ],
'y': [ [] ],
'd': [ [], [] ],
},
2: {
'a': [ [], [], [] ],
'b': [ [], [] ]
}
}
// I want newObj to be:
newObj : {
1: {
'x': [ [], [], [] ],
'y': [ [] ], // don't do anything to existings
'd': [ [] ], // add empty array for new letter key
},
2: {
'a': [ [] ], // add empty array for letter key
'b': [ [] ] // ""
}
}
// And if items removed:
obj : {
1: {
'x': [ [] ]
}
// newObj becomes:
newObj: {
1: {
'x': [ [], [], [] ]
}
}
答案 0 :(得分:0)
试试这个:
function copy(obj, newObj) {
var keys = Object.keys(obj)
keys.map(function(val){
if(newObj.hasOwnProperty(val)){
var keys_two = Object.keys(obj[val])
keys_two.map(function(prop){
if(!newObj.hasOwnProperty(prop)){
var data_two = obj[val][prop]
newObj[val][prop] = data_two;
}
})
} else {
var data = obj[val]
newObj[val] = data;
}
})
}

以下是 jsFiddle