[英]Compare two objects ignoring one key
I have two objects as below: 我有两个对象,如下所示:
obj1 = {"a":"firstValue", "b":"secondValue", "c":"thirdValue157das15714daa4"}
obj2 = {"a":"firstValue", "b":"secondValue", "c":"thirdValue1348sdfsf114sfs45fsd"}
I need to compare both objects ignoring the third key - value pair 'c'. 我需要比较两个对象而忽略第三个键-值对'c'。 Basically the comparison should return
true
ignoring the 'c' 基本上比较应该返回
true
而不考虑'c'
Can anyone help me with an optimistic solution in angular or javascript 谁能帮我提供角度或JavaScript的最佳解决方案
Thanks in advance 提前致谢
Simply 只是
obj1.a == obj2.a && obj1.b == obj2.b
Or if an a
and b
are going to be dynamic, then store keyToIgnore
或者如果
a
和b
将是动态的,则存储keyToIgnore
var keyToIgnore = [ "c" ];
var isEqual = Object.keys( obj1 ).every( s => keyToIgnore.includes(s) || obj1[ s ] == obj2[ s ] );
Demo 演示版
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 ) )
Following is one way to achieve this: 以下是实现此目的的一种方法:
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);
The above first filters out the non-required property and then compares the values of remaining properties in the two objects. 上面的方法首先过滤掉不需要的属性,然后比较两个对象中其余属性的值。
You could check explcit every property of the objects. 您可以检查对象的每个属性是否明确。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.