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