簡體   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