I have a function that can get an array of an arbitary size, along with a value. The function should apply the keys given, to an object that has nested objects, and then set the last key to the value given. It then stores the object somewhere elsewhere.
This is easily done when the amount of keys is known, and consistent (object[key1][key2][key3] = value
), however it seems impossible to do this when the amount of keys given is unknown.
I know I can't do something like this
let foo = object[stack[0]];
stack.slice(1).forEach(key => foo = foo[key]);
foo = value;
Because that will just end up reassigning foo
.
What I want to do is to be able do something like object[stack] = value
, or something similar.
EDIT
It seems that people are interpreting this as getting a nested value, which is not what I want. I want to set a nested value.
Example data for those that asked
let stack = ['a', 'b', 'c', 'd'];
let object = {
a: {
b: {
c: {
d: 'Lorem'
}
}
}
}
// Do something that sets object.a.b.c.d to 'Lorem ipsum' (that isn't reliant on the number of keys)
console.log(object);
/*
{
a: {
b: {
c: {
d: 'Lorem ipsum'
}
}
}
}
*/