Q:

Access to object keys in javascript

I have a json that is something like this:
user = 
    {
       "info": {
                 "id": "....",
                  ......
       },
       ......
     }

So.. i can get the id using user.info.id but i need a function that can give me a property of an object using something like getInfo(user, "info.id") i already tried my luck with user["info.id"].
Has JavaScript already got something like this? Or, how can i implement this?
BTW, I'm using node.js :)

A:

You can use reduce() to create such function.

var user = {
  "info": {
    "id": 3,
  },
}

function getInfo(data, key) {
  return key.split('.').reduce(function(r, e) {
    return r[e]
  }, data)
}

console.log(getInfo(user, "info.id"))

With ES6 arrow function
function getInfo(data, key) {
  return key.split('.').reduce((r, e) => r[e] , data)
}

