Compare keys & values in a JSON object when one object has extra keys in JavaScript


Suppose, we have two JSON objects like these −

const obj1 = {a: "apple", b: "banana", c: "carrot"};
const obj2 = {a: "apple", e: "egg", b: "banana", c: "carrot", d: "dog"};

We are required to write a JavaScript function that takes in two such objects. We want to be able to have a Boolean check comparing the two objects without having to remove data from either one.

For example, if I were to use the data above, the Boolean check should return true because the values of the keys that are in both objects match.

However, let’s say obj1 stays the same but obj2 is the following −

const obj1 = {a: "apple", b: "banana", c: "carrot"}
const obj2 = {a: "ant", e: "egg", b: "banana", c: "carrot", d: "dog"}

With this data, it should return false because a key's value is not matching even though other fields are matching and some fields are not present in both objects.

Example

The code for this will be −

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))

Output

And the output in the console will be −

true
false

Updated on: 21-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements