I'm currently working on optimizing a function that retrieves JSON data stored in localStorage using dot notation. The get()
function provided below is functional, but it feels verbose and limited in its current state.
I believe there's room for improvement by incorporating recursion. Any suggestions on how to refactor this for better efficiency?
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')