compare javascript objects

Asked

Viewed 66 times

3

in this script, which compares objects in javascript, even if I pass equal values (to my understanding, but which all indicates is wrong), the return remains false. someone could help me better understand this concept?

let deepEqual = (a, b) => {
    let aKeys = Object.keys(a);
    let bkeys = Object.keys(b);
    if (aKeys.length !== bkeys.length) {
        return false
    }
    let equals = aKeys.some((chave) => {
        return a[chave]!== b[chave]
    });
    return !equals
}
let obj = {here: {is: "an"}, object: 2};
let obj2 = {here: {is: "an"}, object: 2};
let obj3 = obj2;
console.log(deepEqual(obj, obj));
// true
console.log(deepEqual(obj, obj2));
// false
console.log(deepEqual(obj2, obj3));
// true
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// false

thanks ;)

1 answer

3

The problem with this function is that it compares only the first depth level of the object. That is, when comparing numerical values all right, but when comparing the value of a property that is an object, like {is: "an"}, and in each of the objects, then will give false, because {is: "an"} === {is: "an"} gives false.

What you have to do is that this function is recursive and by detecting an object as the value of that key/property then you have to call yourself and analyze that value of the key/property as an object and do it at every depth level of that object.

An example would be like this:

let deepEqual = (a, b) => {
  let aKeys = Object.keys(a);
  let bkeys = Object.keys(b);
  if (aKeys.length !== bkeys.length) {
    return false
  }
  let equals = aKeys.some((chave) => {
    if (typeof a[chave] === 'object') return !deepEqual(a[chave], b[chave]);
    else return a[chave] !== b[chave]
  });
  return !equals
}
let obj = {
  here: {
    is: "an"
  },
  object: 2
};
let obj2 = {
  here: {
    is: "an"
  },
  object: 2
};
let obj3 = obj2;
console.log(deepEqual(obj, obj)); // true
console.log(deepEqual({foo: 123}, {bar: 345})); // false
console.log(deepEqual(obj, obj2)); // true
console.log(deepEqual(obj2, obj3)); // true
console.log(deepEqual(obj, {here: {is: "an"}, object: 2})); // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.