I have an object
const a = {
b: {
c: "new object",
b: {
c: "new object",
}
}
}
Here, the level of nesting for the key b
is 2. I want to add another
b: {
c: "new object",
}
to the last b
i.e., 2nd level nested b
which will make the object now have 3 level of nested b
The level of nesting is dynamic. It can be 0 as well. That means const a = {}
How can add an object to a nested object, knowing the level of nesting?
eval()
is out of option.
I'm currently doing it with 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"];
thePath.push("b");
}
lodash.set(a, thePath, {
c: "new object"
});
Is there any other approach? Can it be achieved with Object.assign somehow?
CodePudding user response:
You could iterate the object and get finally the target object.
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; }
CodePudding user response:
Even without Object.assign
I was able to make it work.
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"
}
);