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

138
Visualizações
Javascript - Access a nested property on an object from an array of strings

I have an object like this

{
  metadata: {
    correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',
    createdDateTime: '2021-06-15T16:46:24.247Z'
  }
}

and I have an array of the properties I wanna access

[metadata, correlationId]

how can I dynamically access the property on the object? like

keys.forEach((key) => {
  object[key][key2] ???
})

it needs to be dynamic since I don't know how deep we need to access the object

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

0

Here is a solution without recursion:

const myObj = {
    a: {
        b: {
            c: "I'm the target"
        }
    }
}
const keys = ['a', 'b', 'c'];

let result = myObj;
for (const key of keys) {
    result = result[key];
}
console.log(result);

Or with recursion:

const finder = (obj, keys, index = 0) => {
    const result = obj[keys[index++]];
    
    if (!result) {
        return obj;
    }
    return finder(result, keys, index);
}

console.log(finder(myObj, keys));
about 4 years ago · Juan Pablo Isaza Relatório

0

This is pretty similar to Accessing nested JavaScript objects and arrays by string path, except with one fewer step - you already have the keys you need in the form of an array. .reduce and access the next nested value in each iteration.

const obj = {
  metadata: {
    correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',
    createdDateTime: '2021-06-15T16:46:24.247Z'
  }
};
const keys = ['metadata', 'correlationId'];

const result = keys.reduce((a, key) => a[key], obj);
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

This is my idea to solve your problem. Tell me, if is ok for you.

let x = {
  metadata: {
    correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',
    createdDateTime: '2021-06-15T16:46:24.247Z'
  }
}

let fun = x => typeof x === 'string' ? console.log(x) : Object.keys(x).map( y => fun(x[y]));

fun(x);

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