Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 403
Minor Vargas Avatar asked Oct 20 '25 19:10

Minor Vargas


2 Answers

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));
like image 156
MathiusHansek Avatar answered Oct 22 '25 08:10

MathiusHansek


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);
like image 28
CertainPerformance Avatar answered Oct 22 '25 08:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!