javascript - 使用递归进行深度对象比较

标签 javascript recursion arrow-functions

我尝试使用递归进行深度对象比较,但我的函数返回 undefined

我知道有更好的方法来比较对象(IE JSON.Stringify()),但我不明白为什么我的函数返回 undefined

function deepObjCompare(obj1, obj2) {

  Object.keys(obj1).forEach((key) => {
    const key1 = obj1[key];
    const key2 = obj2[key];

    if (key2) {
      if (typeof key1 === "object" && key1 !== null) {
        deepObjCompare(key1, key2);
      } else if (key1 === key2) {
        return true;
      }
    }
    return false;
  });
}

const obj1 = {
  name: "Bill",
  address: {
    cityNow: "Paris",
    cityFuture: "NYC"
  },
  age: 39
};

const obj2 = {
  name: "Bill",
  address: {
    cityNow: "Paris",
    cityFuture: "NYC"
  },
  age: 39
};

const obj3 = {
  name: "Bob",
  address: "Paris",
  age: 39
};

console.log(deepObjCompare(obj1, obj3));

最佳答案

我在这里看到三个主要问题:

  • deepObjCompare 缺少返回语句,这就是它隐式返回 undefined 的原因。
  • .forEach 方法总是返回undefined,因此您需要将其更改为另一个将返回实际值的方法。我认为 .every 是您在这里所追求的。
  • 您不返回递归调用的结果。

总而言之,这会将您的代码段更改为以下内容:

function deepObjCompare(obj1, obj2) {

  return Object.keys(obj1).every((key) => { // Use .every and return the result!
    const key1 = obj1[key];
    const key2 = obj2[key];

    if (key2) {
      if (typeof key1 === "object" && key1 !== null) {
        return deepObjCompare(key1, key2); // Return the result of your recursive call!
      } else if (key1 === key2) {
        return true;
      }
    }
    return false;
  });
}

const obj1 = {
  name: "Bill",
  address: {
    cityNow: "Paris",
    cityFuture: "NYC"
  },
  age: 39
};

const obj2 = {
  name: "Bill",
  address: {
    cityNow: "Paris",
    cityFuture: "NYC"
  },
  age: 39
};

const obj3 = {
  name: "Bob",
  address: "Paris",
  age: 39
};

console.log(deepObjCompare(obj1, obj3)); // false
console.log(deepObjCompare(obj1, obj2)); // true

关于javascript - 使用递归进行深度对象比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52523446/

相关文章:

javascript - 文件夹共享容器中的 Nextjs 页面

Javascript 多个文件中的一个函数名称

windows - 如何使用 DOS 命令以编程方式将存档解压缩到 Windows 上自己的目录中?

javascript - 了解 .reduce() 中的许多函数参数

javascript - 将鼠标悬停在切换两个类上后点击事件问题

javascript - 正确跟踪鼠标悬停在哪个(嵌套)div 上

Java - 数字的递归和及其工作原理

python - 这个递归在 python 中是如何工作的?

javascript - react : Rendering a method defined inside arrow function?

Javascript 箭头函数代替 for...of