Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda