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

99
Vistas
How to set value of multidimential object when name path is stored in array of unknown length?

I have an array of unknown length which defines the path to content I want to alter in a object.

This is what I want.

let updatedContent = "Hello World!";
let myArray = ["layer1","layer2","layer3"];
myObject["layer1"]["layer2"]["layer3"] = updatedContent;

My problem is myArray is of unknown length. What is the best way to update a value in the object?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here's an ugly approach using a recursive function. The idea is retrieving the nested properties in sequence, calling the function recursivelly with the current level, until the end of the array:

function changeObject(obj, arr, content, index = 0) {
  if (index < arr.length - 1) {
    changeObject(obj[arr[index]], arr, content, ++index);
  } else {
    obj[arr[index]] = content;
  }
};

const myObject = {
  layer1: {
    layer2: {
      layer3: "foo"
    }
  }
};

let updatedContent = "Hello World!";
let myArray = ["layer1", "layer2", "layer3"];
myObject["layer1"]["layer2"]["layer3"] = updatedContent;

changeObject(myObject, myArray, updatedContent);
console.log(myObject);

about 4 years ago · Juan Pablo Isaza Denunciar
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