Access nested objects and arrays using string path 1

Access nested objects and arrays using string path

//to get
const resolvePath = (object, path) => path.split('.').reduce((o, p) => o?.[p], object)

//to get, returning a default value if not found
const resolvePath = (object, path, defaultValue) => path.split('.').reduce((o, p) => ?.[p] ?? defaultValue, object)

//to set
const setPath = (object, path, value) => path.split('.').reduce((o,p,i) => o[p] = path.split('.').length === ++i ? value : o[p] || {}, object)

Here is what the above code is Doing:
1. Split the path into an array of keys
2. Reduce the array of keys into a single value
3. If the key is not found, return undefined
4. If the key is found, return the value

Similar Posts