0

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')
Ed Williams
  • 2,447
  • 3
  • 15
  • 21

1 Answers1

0

You can use the lodash.get (documentation) which works just fine.

const get = require('lodash.get');

get('first')
get('first.second')
get('first.second.third')
Kmaschta
  • 2,369
  • 1
  • 18
  • 36