javascript - Javascript:在递归遍历期间设置对象的参数?
问题描述
我正在尝试遍历一个对象并对其进行更改。
我能够拼接嵌套在母对象深处的对象
我无法将新对象分配给母对象的深层参数。
我以为我会通过引用传递并且能够对母对象进行更改?(有时我得到的对象相对于我需要的路径是不完整的,所以我必须将字符串更改为对象以允许遍历继续)
这是代码:-
let obj: any = history.present;
let path = ['the','path',0,'to','the',3,'target'];
for (i = 0; i < path.length; i++){
if(typeof obj === 'string' &&
Object.keys(manifest.history.present.manifest.assetCatalog).includes(obj)){
obj = {item: obj};
// this isn't changing the corresponding parameter in history.present
}
obj = obj[path[i]];
}
解决方案
好吧,我修好了。关键是在我知道它们丢失时将属性设置在下游一点,而不是尝试将它们设置在我正在检查的对象上。
let obj: any = history.present;
let path = ['the','path',0,'to','the',3,'target'];
for (i = 0; i < path.length; i++){
obj = obj[path[i]];
if(typeof obj === 'string' && Object.keys(assetCatalog).includes(obj)){
// some code to build out obj's structure to accept the right kind of reassignment when necessary
obj['new']['structure'] = {item: obj};
}
}