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

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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