Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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)
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Access #nested #objects #arrays #string #path
ADD COMMENT
Topic
Name
4+9 =