Javascript:在递归遍历期间设置对象的参数?

问题描述

我正在尝试遍历一个对象并对其进行更改。

我能够拼接嵌套在母对象深处的对象

我无法将新对象分配给母对象的深层参数

我以为我会通过引用传递并且能够对母对象进行更改? (有时我得到的对象相对于我需要的路径是不完整的,所以我必须将字符串更改为对象以允许继续遍历)

这是代码:-

let obj: any = history.present;
let path = ['the','path','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','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};
  }
}