json property getter

json property getter

by eitanp461

JavaScript

var json = {
  "path": {
    "index": "abc",
    "devices": "",
    "myobj": {
      "myprop": "wowza"
    }
  }
}


var getProperty = function(json, prop) {
  var tokens = prop.split('.'); // ['path', 'myobj', 'myprop']
  return tokens.reduce(
    function reducer(accumulator, currentValue) {
      return accumulator && accumulator[currentValue]
    }, json);
}

var prop = 'path.myobj.myprop';
// json["path"]["myobj"]["myprop"]
console.log(getProperty(json, prop)) // "wowza"
console.log(getProperty(json, 'path.index')) // "abc"