Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda