Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var _ = require('lodash'
- )
- function getValueFromPath(path, obj, val) {
- let key = path.shift('.')
- // check for bracket notation
- if (key.indexOf('[') > -1) {
- const match = key.match(/(\w+)\[(\d+)\]/)
- if (match !== null) {
- key = match[2]
- obj = obj[match[1]]
- }
- }
- // Return the value if done, otherwise, keep going
- return path.length === 0 ? (val !== undefined ? obj[key] = val : obj[key]) : getValueFromPath(path, obj[key], val)
- }
- function isLeaf(str) {
- return str.length === -1
- }
- function getNodeValue(path, obj, separator){
- // console.log('will search for data on path', path, obj)
- if(!path.length) return obj
- return path.indexOf(separator) > 0 ? _.find(obj[path.split(separator)[0]], { id: path.split(separator)[1] }) : obj[path]
- }
- function getValueSafe(path, obj, sep) {
- if (!sep) sep = path.indexOf('|') === -1 ? ':' : '|'
- try {
- const [p1, ...p2] = path.split('.')
- obj = getNodeValue(p1, obj, sep)
- const remainder = p2.join('')
- // console.log('new obj & remainder', obj, remainder)
- return remainder.indexOf('.') !== -1 ? getValueSafe(remainder, obj, sep) : getNodeValue(remainder, obj, sep)
- } catch (e) {
- console.log(e)
- throw new Error('Path may contain an invalid ID.')
- }
- }
- const foo = {
- prop: "foo",
- content: [
- {
- id: "aaa",
- obtainFromMunicipality: [
- {
- id: "bbb"
- },
- {
- id: "ccc"
- }
- ]
- }
- ]
- }
- console.log(getValueSafe('content:aaa', foo))
- console.log(getValueSafe('content:aaa.obtainFromMunicipality', foo))
- console.log(getValueSafe('content:aaa.obtainFromMunicipality:ccc', foo))
Add Comment
Please, Sign In to add comment