0

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

  1. That question does not address the last part of this one,
  2. 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
  3. 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);
DexieTheSheep
  • 439
  • 1
  • 6
  • 16
  • 1
    You want to write/find a parser? [There are many examples](https://www.google.com/search?q=javascript+parse+dot+notation+set+object+site:stackoverflow.com). and just because they might be old, they can be used in a question on how to update such a script to ES6+ or similar - for example https://stackoverflow.com/questions/10934664/convert-string-in-dot-notation-to-get-the-object-reference – mplungjan Jan 10 '22 at 06:55
  • 1
    @mplungjan Found out from the first result's third answer, plus a little more searching, about lodash's "get" and "set" functions, thanks for the help! – DexieTheSheep Jan 10 '22 at 07:06

0 Answers0