I'm writing a function to access JSON (in localStorage) with a dot notation. The get()
function below works, but is verbose (and limited)
I'm sure there's a better way of refactoring this with recursion. Any ideas?
get(str) {
var keys = str.split('.')
var parent = JSON.parse({"first":{"second":{"third":{"something":"here"}}}})
if ( keys.length === 1 ) return parent
if ( keys.length === 2 ) return parent[keys[1]]
if ( keys.length === 3 ) return parent[keys[1]][keys[2]]
if ( keys.length === 4 ) return parent[keys[1]][keys[2]][keys[3]]
}
get('first')
get('first.second')
get('first.second.third')