0

Say I have an object

const someObject = {
    foo: 'bar',
    baz: {
        abc: [
            'def',
            'ghi'
        ]
    }
}

And a dynamically generated array with a path to the value needed

const someArray = ['baz', 'abc', 1]

How can I access the object value based on array values?

In the example it would return 'ghi'

maafk
  • 6,176
  • 5
  • 35
  • 58

1 Answers1

1

You could do that dynamically, using structuredClone to take a copy from someObject and loop over array of keys someArray each iteration update cloneSomeObject with new value of that object:

const someObject = {
    foo: 'bar',
    baz: {
        abc: [
            'def',
            'ghi'
        ]
    }
}
const someArray = ['baz', 'abc', 1];
let cloneSomeObject = structuredClone(someObject);
for(let key of someArray){
 cloneSomeObject = cloneSomeObject[key]
}
console.log(cloneSomeObject);//ghi
XMehdi01
  • 5,538
  • 2
  • 10
  • 34