javascript - 比较两个Object,判断不同属性的父节点

标签 javascript reactjs

我有一个场景,需要比较 treeObject1 和 treeObject2 以确定属性级别的确切差异并找到修改节点的父节点。

在下面提供的对象中,我需要将输出输出为蓝色。由于差异在 otherObj2。

treeObject1  = {
color: "red", 
value: 10, 
otherObj: { 
   color: "blue", 
   otherObj2: { 
     otherColor: "blue", 
     otherValue: 20,
    }
}
}

treeObject2  = {
color: "red", 
value: 10, 
otherObj: { 
   color: "blue", 
   otherObj2: { 
     otherColor: "Green", 
     otherValue: 20,
    }
}
}

最佳答案

如果您还想要 key “otherObj”,请告诉我,可以轻松添加。否则,这是您正在寻找的工作版本。

这使用了 Object.keys 的组合和 every

treeObject1 = {
  color: "red",
  value: 10,
  otherObj: {
    color: "blue",
    otherObj2: {
      otherColor: "blue",
      otherValue: 20,
    }
  }
}

treeObject2 = {
  color: "red",
  value: 10,
  otherObj: {
    color: "blue",
    otherObj2: {
      otherColor: "Green",
      otherValue: 20,
    }
  }
}

const findParentNode = (obj1, obj2, parent = null) => {
   
   if(parent === null) parent = obj2;

   //since the structures are the same we only get keys from the first object
   const keys = Object.keys(obj1);
   
   let result = null;
   //iterate through every key
   keys.every(key=>{
     //if it's an object... then we recall findParentNode (recursive)
     if(obj1[key] instanceof Object){
        result = findParentNode(obj1[key], obj2[key], obj2);
        //If result from findParentNode is not null then a difference was found. 
        //Return false to stop the every method.
        if(result !== null) return false;
        
     }else if(obj1[key] !== obj2[key]){
        //If the objects are different we found a difference
        //Set the parent as the difference
        result = parent;
        return false;
     }
     //return true to keep on looping
     return true;
  });
  //return the result
  return result;
}

console.log(findParentNode(treeObject1, treeObject2));

** 请注意,如果未找到任何内容,上述代码段将返回“null”。 **

关于javascript - 比较两个Object,判断不同属性的父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51892394/

相关文章:

javascript - 如何阻止第二个 React 计时器从零循环回来?

javascript - 如何从数组中的范围中删除项目

javascript - 用于电子商务网站开发的 HTML、Angular Js 和 Css

javascript - Redux状态树结构: "same type of data with different format/amounts of detail"

reactjs - 为什么 jsx 中的三元运算符不起作用

javascript - react 重置按钮清除文本输入区域,javascript

javascript - 如何使用 Webpack 代码分割来处理部署?

javascript - 将 48khz 下采样到 16khz - Javascript

javascript - jQuery 键盘事件

javascript - 在 console.log 中,状态已更新,它也通过 props 反射(reflect)出来,但是组件没有重新渲染