繁体   English   中英

比较两个对象并确定具有不同属性的父节点

[英]Compare two Objects and determine the parent node of differed properties

我有一个场景,需要比较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,
    }
}
}

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

这里使用的组合Object.keysevery

 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”。 **

您可以对对象使用嵌套方法并检查值。

 function getDiffParents(object1, object2, parent = {}) { return Object.assign(...Object.entries(object1).map(([k, v]) => v && typeof v === 'object' ? getDiffParents(v, object2[k], object1) : v === object2[k] ? {} : parent )); } var 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 } } }; console.log(getDiffParents(treeObject1, treeObject2)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM