0

Given a property accessor in dot notation eg. google.maps.places, I need to evaluate the statement to get the property value.

var str = 'google.maps.places';
var statement = 'window["' + str.split('.').join('"]["') + '"]';
eval(statement);

Ofcourse, it works but I've never used eval in production and would never want to, so just wondering if there's a better way? Also because this is a quick example but the function could accept accessors of any levels, just google or google.maps or even google.maps.places.autocomplete.

eozzy
  • 66,048
  • 104
  • 272
  • 428

1 Answers1

2

You can use split() and reduce()

let obj = {
  google:{
    maps:{
      places:["Place 1","place 2"]
    }
  }
}
function findItem(obj,path){
      path = path.split('.');
      return path.reduce((ac,a) => (ac.hasOwnProperty(a) ? ac[a] : {}),obj);
}

console.log(findItem(obj,'google.maps.places'))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73