我试图仅通过KEYS比较对象。
var obj1 = [ {"depid": "100", "depname": ""}, {"city": "abc", "state": "xyz"}, {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}} ];
var obj2 = [ {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}}, {"depid": "100", "depname": "role"}, {"city": "abc", "state": "xyz"} ];
例如,如果我们比较obj1中的对象{" depid":" 100"," depname": ""}使用obj2 {" depid":" 100"," depname":" role"},必须返回true。 由于键是相同的。我需要在obj1中设置obj2的值。
//Expected result
obj1 = [ {"depid": "100", "depname": "role"}, {"city": "abc", "state": "xyz"}, {"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}} ]
I have tried the solution provided in this link但仍然无法只对对象键进行比较并将值从obj2更新为obj1
答案 0 :(得分:0)
此函数检查:对于obj1中的每个对象,它将查找obj2中的每个键。所以它检查obj2中是否存在deptid,如果是则返回true。如果
var f = function(obj1, obj2){
console.log('Starting...', obj1.length);
for(var i in obj1){
var memberObj1 = obj1[i];
var memberObj1Keys = Object.keys(memberObj1);
console.log('Keys in each object', memberObj1Keys);
// console.log('Checking for ', memberObj1);
for(var j in obj2){
var memberObj2 = obj2[j];
console.log('Object2 ', memberObj2);
for(var eachKey in memberObj1Keys){
console.log('Looking for %s in obj2', memberObj1Keys[eachKey]);
if(memberObj2[memberObj1Keys[eachKey]]){
console.log('Found');
return true;
}
}
}
console.log('======================');
}
return false;
}
使用该功能。
var result = f(obj1, obj2);
console.log(result);
这是您的问题的快速实施。到目前为止,我还没有尝试优化循环。
欢迎任何编辑。