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

85
Visualizações
How do you get value from multidimential object when name path is stored in array of unknown length?

I'm creating a folder directory and need to allow users to navigate within it. I have a global variable that stores their location in the directory. How can I access the content within their selected folder.

This is what I what.

let location = ["2022","March","Week4"];
let content = folderInformation["2022"]["March"]["Week4"];

However, the file names "2022, March, Week4, ect" are set by the user.

So I could do this.

let location = ["2022","March","Week4"];
let layer1 = location[0];
let layer2 = location[1];
let layer3 = location[2];
let content = folderInformation[layer1][layer2][layer3];

However, the user could be 2 layers deep or 15.

I tried

let layers = location.join("][");
let content = folderInformation[layers];

and

let layers = "["+location.join("][")+"]";
let content = folderInformation+layers;

with no success. What is the best option to access the content within the object?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A short version with reduce:

const content = location.reduce((o,l)=>o?.[l],folderinformation);
about 4 years ago · Juan Pablo Isaza Relatório

0

Loop through your array of locations and access every location in the folderInformation object one by one. This way you will go one level deeper with each iteration.

function getFolderInformation(folderInformation, locations) {
  let currentLocation = folderInformation;
  
  for (const location of locations) {
    if (location in currentLocation) {
      currentLocation = currentLocation[location];
    }
  }
  
  return currentLocation;
}

const folderInformation = {
  '2022': {
    'Februari': {
      'Week1': {
        title: 'Nope',
        description: 'Not this one'
      }
    },
    'March': {
      'Week3': {
        title: 'Also no',
        description: 'Wrong'
      },
      'Week4': {
        title: 'Foo',
        description: 'Bar'
      },
    }
  }
};

let locations = ["2022", "March", "Week4"];
let content = getFolderInformation(folderInformation, locations);

console.log(content);

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