I have an array like ['animals', 'cats', 'cute', 'fast', 'small', ...]
, and want to access nested keys of the object like
let object = { one: { two: { three: { // and so on } } } }
Usually I would write object['animals']['cats']['cute']['fast']['small']..
The problem is that keys and the number of levels are dynamic (so I can get objects with 2 nested levels or 50), so I have no idea how it can be done
Thanks in advance for any help
Advertisement
Answer
Iterate over the array of keys with .reduce
, where the accumulator is the current nested object:
let object = { one: { two: { three: { prop: 'val' } } } }; const props = ['one', 'two', 'three', 'prop']; const nestedVal = props.reduce((a, prop) => a[prop], object); console.log(nestedVal);
To assign a value at the same point, first pop off the last key, use the same reduce
trick to get to the last object, and assign to the property at the last key with bracket notation:
let object = { one: { two: { three: { prop: 'val' } } } }; const props = ['one', 'two', 'three', 'prop']; const lastKey = props.pop(); const nestedObj = props.reduce((a, prop) => a[prop], object); nestedObj[lastKey] = 'newVal'; console.log(object);