如何将一个对象添加到嵌套对象中,同时知道该对象应添加到的嵌套级别



我有一个对象

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

这里,密钥b的嵌套级别为2。我想添加另一个

b: {
c: "new object",
}

到最后一个b,即第二级嵌套b,这将使对象现在具有第三级嵌套的b

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

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

eval()不可用。

我目前正在用洛达什做这件事。

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

还有其他方法吗?用Object.assign可以实现吗?

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

const object = { b: { b: { l: 2 }, l: 1 }, l: 0 };
let temp = object,
depth = 2;
while (depth--) temp = temp.b;
console.log(temp);
Object.assign(temp, { payload: 'foo' });
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

即使没有Object.assign,我也能让它工作。

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

最新更新