hanki.dev

Access nested object property with variable

Let's say you have an object like this:

const myObject = {
  first: {
    second: {
      third: {
        lost: 'found',
      },
    },
  },
};

And for some reason you need to access a nested key, with a variable. Using the variable as an expression doesn't just work with nested keys.

const getterString = 'first.second.third.lost';
console.log(myObject[getterString]); // Output: undefined

Using reduce, we can easily make a function to retrieve the nested key, with a variable!

const getKey = (obj, key) => key.split('.').reduce((acc, cur) => acc[cur], obj);
console.log(getKey(myObject, getterString)); // Output: 'found'

#javascript

- 2 toasts