gpt4 book ai didi

javascript - 如果我不知道它们有多少节点/子对象,则循环嵌套对象?

转载 作者:行者123 更新时间:2023-12-01 01:31:14 25 4
gpt4 key购买 nike

如果我不知道嵌套对象有多少个子对象,如何循环它们?

例如,如果我想用另一个对象(代码示例)更新旧对象,我需要遍历对象中的每个节点,逐一检查键/值是否匹配。

var savedData = {
"a": {
"x": {
"foo": 1,
"foofoo": 11
},
"y": {
"bar": 2,
"barbar": 22
}
},
"b": {
//...
},
"c": {
//...
}
};


var newData = {
"a": {
"x": {
"foo": 7 //<== new value to be changed;
//<== notice there were "foofoo" key here, we need to keep this key and does NOT remove it;
},
"y": {
"bar": 8 //<== new value to be changed;
//<== notice there were "barbar" key here, we need to keep this key and does NOT remove it;
},
"z": { //<== this is a brand new child object to be added to the savedData;
"baz": 9
}
}
};


updateSavedData(newData);


function updateSavedData(newData) {

if (savedData) {
Object.keys(savedData).forEach(function(savedKeyLevel1) {
Object.keys(newData).forEach(function(newKeyLevel1) {

if (savedKeyLevel1 === newKeyLevel1) {
console.log('the key [' + savedKeyLevel1 + '] exist among the saved and the new data!');
if (jQuery.type(savedData[savedKeyLevel1]) === "object") {
console.log('the key [' + savedKeyLevel1 + '] is an object!');
//start looping again, but this time in a deeper level of this child object...
Object.keys(savedData[savedKeyLevel1]).forEach(function(savedKeyLevel2) {
Object.keys(newData[newKeyLevel1]).forEach(function(newKeyLevel2) {
if (savedKeyLevel2 === newKeyLevel2) {
console.log('the key [' + savedKeyLevel1 + ' -> ' + savedKeyLevel2 + '] exist among the saved and the new data!');
//...
//<== my question is about what to do here?
//if I don't know how much deeper the savedData is.
} else {
//this is a brand new child object, add it to the tree;
savedData[savedKeyLevel1][newKeyLevel2] = newData[newKeyLevel1][newKeyLevel2];
}
});
});

}
} else {
//this is a brand new child object, add it to the tree;
savedData[newKeyLevel1] = newData[newKeyLevel1];
}
});
});

} else {
savedData = newData;
}

console.log('The savedData after update is:\n', JSON.stringify(savedData));

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我的问题是:

如果我不知道物体有多深怎么办?

我在这里寻找什么来阅读/尝试?

最佳答案

您可能使事情变得比需要的更复杂一些。只要它是一个具有嵌套对象和属性的简单对象,您就可以测试对象并递归:

var savedData = {"a": {"x": {"foo": 1,"foofoo": 11},"y": {"bar": 2,"barbar": 22}},"b": {},"c": {}};
var newData = {"a": {"x": {"foo": 7},"y": {"bar": 8 },"z": { "baz": 9}}};

function merge(data, newdata){
for (let key in newdata){
if (typeof data[key] == 'object') merge(data[key], newdata[key])
else data[key] = newdata[key]
}
}
merge(savedData, newData)
console.log(savedData)

关于javascript - 如果我不知道它们有多少节点/子对象,则循环嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com