这些是我的两个对象
var obj1={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj2={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com","address":"New York"}
obj1是动态的,我们不知道第一个作为属性的内容,如果obj1属性与值一起存在于obj2属性中,我想返回true,并且如果obj2中不存在任何一个具有其值的对象属性,那么它应该如何做到这一点,你们有什么想法吗?
答案 0 :(得分:0)
你可以使用像lodash这样的库来做这件事,但是如果你想要一个简单易行的答案,你可以这样做(因为“Object.keys”而没有在ie8上工作):
var equal = true;
if(Object.keys(obj1).length == Object.keys(obj2).length)
for(i in obj1){
if(typeof(obj2[i]) == 'undefined') equal = false;
}
else equal = false;
console.log(equal);
答案 1 :(得分:0)
将两个对象混合在一起,看看结果是否等于你要检查的结果:
function check(obj1, obj2){
var obj3 = angular.extend({}, obj2, obj1);
return angular.equals(obj3, obj2);
}
JSfiddle显示结果:http://jsfiddle.net/0p59ya5a/
var obj1={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj2={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com","address":"New York"}
console.log(check(obj1, obj2)); //true
var obj3={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj4={"firstName":"john","lastName":"Peter","address":"New York"}
console.log(check(obj3, obj4)); //false
var obj1={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj2={"firstName":"jim","lastName":"Peter","email":"rasheed@gmail.com","address":"New York"}
console.log(check(obj5, obj6)); //false