我有两个对象如下:
obj1 = {"a":"firstValue", "b":"secondValue", "c":"thirdValue157das15714daa4"}
obj2 = {"a":"firstValue", "b":"secondValue", "c":"thirdValue1348sdfsf114sfs45fsd"}
我需要比较两个对象,忽略第三个键 - 值对'c'。基本上,比较应该返回true
忽略'c'
任何人都可以帮助我使用angular或javascript中的乐观解决方案
提前致谢
答案 0 :(得分:3)
简单地
obj1.a == obj2.a && obj1.b == obj2.b
如果a
和b
是动态的,那么请存储keyToIgnore
var keyToIgnore = [ "c" ];
var isEqual = Object.keys( obj1 ).every( s => keyToIgnore.includes(s) || obj1[ s ] == obj2[ s ] );
<强>演示强>
var obj1 = {
"a": "firstValue",
"b": "secondValue",
"c": "thirdValue157das15714daa4"
}
var obj2 = {
"a": "firstValue",
"b": "secondValue",
"c": "thirdValue1348sdfsf114sfs45fsd"
}
var keyToIgnore = [ "c" ];
var fnCompare = ( obj1, obj2 ) => Object.keys(obj1).every(s => keyToIgnore.includes(s) || obj1[s] == obj2[s]);
console.log( fnCompare( obj1, obj2 ) )
&#13;
答案 1 :(得分:1)
以下是达到此目的的一种方法:
const obj1 = {
"a": "firstValue",
"b": "secondValue",
"c": "thirdValue157das15714daa4"
};
const obj2 = {
"a": "firstValue",
"b": "secondValue",
"c": "thirdValue1348sdfsf114sfs45fsd"
};
const result = Object
.keys(obj1)
.filter(k => k !== 'c')
.every(k => obj1[k] === obj2[k]);
console.log(result);
&#13;
上面首先筛选出非必需属性,然后比较两个对象中剩余属性的值。
答案 2 :(得分:1)
您可以检查explcit对象的每个属性。
function check(o1, o2) {
const filter = v => v !== 'c' ;
var keys1 = Object.keys(o1).filter(filter),
keys2 = Object.keys(o2).filter(filter);
return keys1.length === keys2.length && keys1.every(k => o1[k] === o2[k]);
}
var obj1 = { a: "firstValue", b: "secondValue", c:"thirdValue157das15714daa4" },
obj2 = { a: "firstValue", b: "secondValue", c: "thirdValue1348sdfsf114sfs45fsd" };
console.log(check(obj1, obj2));
&#13;