【问题标题】:How to add an object to a nested object, knowing the level of nesting to which the object should be added?如何将对象添加到嵌套对象,知道对象应添加到的嵌套级别?
【发布时间】:2023-01-12 03:35:34
【问题描述】:

我有一个对象

const a = {
  b: {
    c: "new object",
    b: {
      c: "new object",
    }
  }
}

在这里,键b的嵌套级别是2。我想再添加一个

 b: {
   c: "new object",
 }

到最后一个b,即第二层嵌套b,这将使对象现在有 3 层嵌套b

嵌套级别是动态的。也可以为 0。这意味着const a = {}

如何在知道嵌套级别的情况下将对象添加到嵌套对象?

eval() 无法选择。

我目前正在用 lodash 做这件事。

let currentObj = a;
const thePath = ["b"];
// checking if "b" is present in the object and nesting if present
while (currentObj["b"]) {
  currentObj = currentObj["b"];
  rendererPath.push("b");
}
lodash.set(a, thePath, {
  c: "new object"
});

还有其他方法吗?可以通过 Object.assign 以某种方式实现吗?

【问题讨论】:

    标签: javascript typescript object lodash nested-object


    【解决方案1】:

    您可以迭代对象并最终获得目标对象。

    const object = { b: { b: { l: 2 }, l: 1 }, l: 0 };
    let temp = object,
        depth = 2;
    
    while (depth--) temp = temp.b;
    
    Object.assign(temp, { payload: 'foo' });
    
    console.log(object);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多