[英]How to compare Two objects based of their keys?
I would like to compare 2 object using their keys. 我想使用它们的键比较2个对象。 If the objects have the same keys, check their values. 如果对象具有相同的键,请检查其值。 If the same save one instance of the pair in a new Object, otherwise save the pair whose value is 1 in the new Objects. 如果相同,则在新对象中保存该对的一个实例,否则在新对象中保存值为1的对。 Here is my attempt: 这是我的尝试:
var sameKey = false;
function hasSameProps( obj1, obj2 ) {
for (var x in obj1){
if (obj2.hasOwnProperty(x)){ // check if the objects have same key
samekey = true;
}
if (sameKey){
}
}
}
var obj1 = {'a':0,'s':0};
var obj2 = {'a':0,'s':1};
hasSameProps( obj1, obj2 ); // should return new Object { 'a':0,'s':1};
You can add the logic inside the if (obj2.hasOwnProperty(x))
like: 您可以在if (obj2.hasOwnProperty(x))
内部添加逻辑,如下所示:
if (obj2.hasOwnProperty(x)) {
newObj[x] = obj1[x] > obj2[x] ? obj1[x] : obj2[x];
}
var sameKey = false; function hasSameProps(obj1, obj2) { var newObj = {}, samekey; for (var x in obj1) { if (obj2.hasOwnProperty(x)) { newObj[x] = obj1[x] > obj2[x] ? obj1[x] : obj2[x]; } } return newObj; } var obj1 = { 'a': 0, 's': 0 }; var obj2 = { 'a': 0, 's': 1 }; console.log(hasSameProps(obj1, obj2));
function hasSameProps( obj1, obj2 ) {
var returnValue = {};
for (var x in obj1) {
returnValue[x] = obj1[x];
if( obj2.hasOwnProperty(x)){
if(obj2[x] == 1) {
returnValue[x] = obj2[x];
}
}
}
return returnValue;
}
var obj1={'a':0,'s':0};
var obj2={'a':0,'s':1};
var obj3 = hasSameProps( obj1, obj2 );
console.log(obj3);
So: both key and value the same, put in new object; 因此:键和值都相同,放入新对象; key same, but not value, then put in new object with value 1? 键相同,但不是值,然后放入值1的新对象?
var obj1 = { 'a': 0, 's': 0 };
var obj2 = { 'a': 0, 's': 1 };
var newObj = {};
for (var x in obj1) {
if (obj2[x] && obj2[x] == obj1[x]) {
newObj[x] = obj1[x];
}
else if (obj2[x] && obj2[x] !== obj1[x]){
newObj[x] = 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.