Skip to content

Instantly share code, notes, and snippets.

@jaredreich
Last active March 28, 2018 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredreich/7761045d2656eb09d31170b65d8332df to your computer and use it in GitHub Desktop.
Save jaredreich/7761045d2656eb09d31170b65d8332df to your computer and use it in GitHub Desktop.
Check and return nested javascript object via key (array support)
const get = (obj, target, fallback) => {
try {
return eval(`obj${target}`)
} catch (e) {
return fallback
}
}
const obj = {
a: {
b: [
{ c: 'wow' },
{ d: 'bam' }
],
e: {
f: 'zap'
}
},
z: [
{
name: 'jane'
}
]
}
const arr = [
'jane'
]
get(obj, '.z[0].name') // jane
get(obj, '.a') // { b: ..., e: ... }
get(obj, '.a.e.f') // 'zap'
get(null, '.a.e.f') // undefined
get(undefined, '.a.e.f', 'fallback') // 'fallback'
get(obj, '.a.b') // [{ c: 'wow' }, { d: 'bam' }]
get(obj, '.a.b[1].d') // 'bam'
get(obj, '.a.b[3].d') // undefined
get(obj, '.a.b[3].d', undefined) // undefined
get(obj, '.a.b[3].d', null) // null
get(obj, '.a.b[3].d', 'fallback') // 'fallback'
get(obj, '.x') // undefined
get(arr, '[0]') // jane
get(arr, '[1]') // undefined
get(arr, '.y', null) // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment