How do you compare keys & values in a JSON objects when one object has extra keys using Lodash?

Viewed 849

I have two JSON objects like so:

var obj1 = {a: "apple", b: "banana", c: "carrot"}
var obj2 = {a: "apple", e: “egg” b: "banana", c: "carrot", d: "dog"}

I 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, lets say obj1 stays the same but obj2 is the following:

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

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

Any ideas? I would prefer to use Lodash since they have a quality library. Originally was trying to use _.isEqual(obj1, obj2) but it doesn't work for my exact needs.

2 Answers

I don't know if lodash has such a method. But you can achieve the same result by just utilizing Object.etnries and Array.every methods.

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


var obj3 = {a: "apple", b: "banana", c: "carrot"}
var 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; // pick the shorter array
  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))

_.isMatch can be of help. Check the below snippet

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

console.log(_.isMatch(obj2, obj1));

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

console.log(_.isMatch(obj2, obj1));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

Note that _.isMatch(obj1, obj2) will not work. You will need to put some logic to determine which object has more keys and pass it as first argument.

Related