Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Set value in object at dynamic key, possibly further than first given scope

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);

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!