milnode
Version:
Vue.js Component Framework, build on top of vuetify
24 lines (18 loc) • 701 B
JavaScript
export function getNestedValue (obj, path, fallback) {
const last = path.length - 1
if (last < 0) return obj === undefined ? fallback : obj
for (let i = 0; i < last; i++) {
if (obj == null) {
return fallback
}
obj = obj[path[i]]
}
if (obj == null) return fallback
return obj[path[last]] === undefined ? fallback : obj[path[last]]
}
export function getObjectValueByPath (obj, path, fallback) {
if (!path || path.constructor !== String) return fallback
path = path.replace(/\[(\w+)\]/g, '.$1') // convert indexes to properties
path = path.replace(/^\./, '') // strip a leading dot
return getNestedValue(obj, path.split('.'), fallback)
}