I have 2 user-provided strings acting as a key, and a value. Let's say, for example, "foo"
and "Hello World!"
. I have an object that I want to modify, and set obj.foo
to Hello World!
.
The problem is that the key can lead to an indefinitely nested object. For example, I should be able to use the key foo.bar[baz].qux
or any strange JS-syntax sequence like that to set a value inside a nested object, or declare one if necessary.
Furthermore, I'm gonna have to access these values with another user-provided string that could be in a different format (for example, foo[bar][baz][qux]
instead). Is there a way to do all of this without using eval()
?
Before someone marks it, this question isn't a duplicate of change structure of an object javascript because
- That question does not address the last part of this one,
- It's 7 years old, and interacting with objects has become a lot easier over updates (maybe my question would be easier to answer with recent versions?) and
- It also doesn't address using [] (not as big of a problem, until you have people using both types in one long expression)
const key = "foo.bar";
const key2 = "foo[bar].baz";
const val = "Hello World!";
let obj = {}
obj[key] = val;
/* Doesn't work. Object is:
* {"foo.bar": "Hello World!"}
* but intended output is
* {"foo": {"bar": "Hello World!"}}
*/
obj[key2] = val;
// Output: {"foo[bar].baz": "Hello World!"}
// Intended: {"foo": {"bar": {"baz": "Hello World!"}}}
console.log(obj);