当一个对象在JavaScript中具有额外的键时,比较JSON对象中的键和值
假设我们有两个像这样的JSON对象-
const obj1 = {a: "apple", b: "banana", c: "carrot"}; const obj2 = {a: "apple", e: "egg", b: "banana", c: "carrot", d: "dog"};
我们需要编写一个接受两个这样的对象的JavaScript函数。我们希望能够进行布尔检查以比较两个对象,而不必从任何一个中删除数据。
例如,如果我要使用上面的数据,则布尔检查应返回true,因为两个对象中的键的值都匹配。
但是,假设obj1保持不变,但obj2如下-
const obj1 = {a: "apple", b: "banana", c: "carrot"} const obj2 = {a: "ant", e: "egg", b: "banana", c: "carrot", d: "dog"}
使用此数据,它应该返回false,因为即使其他字段匹配且两个对象中都不存在某些字段,但键的值不匹配。
示例
为此的代码将是-
const obj1 = { a: "apple", b: "banana", c: "carrot" } const obj2 = { a: "apple", b: "banana", c: "carrot", d: "dog", e: "egg" } const obj3 = {a: "apple", b: "banana", c: "carrot"} const obj4 = {a: "ant", e: "egg" ,b: "banana", c: "carrot", d: "dog"} function checkEquality(a, b) { const entries1 = Object.entries(a); const entries2 = Object.entries(b); const short = entries1.length > entries2 ? entries2 : entries1; const long = short === entries1 ? b : a; const isEqual = short.every(([k, v]) => long[k] === v); return isEqual; } console.log(checkEquality(obj1, obj2)) console.log(checkEquality(obj3, obj4))
输出结果
控制台中的输出将是-
true false