4

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

1
  • What is your intended output value to look like? Commented Aug 2, 2021 at 17:11

3 Answers 3

4

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));
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

3 Comments

I'm pretty sure he's looking for recurrent algorithm to handle any level of depth.
ah ok, I understood, wait a minute.
check this code, is it better? Now it is recursive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.