0

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 :)

2
  • 1
    You can access properties using [] syntax: user["info"]["id"]. So just implement a function that will transform your input into valid JS Commented Jan 12, 2017 at 12:37
  • Well.. how can i go about it? I can have more then only one "." or .. even none Commented Jan 12, 2017 at 12:40

1 Answer 1

0

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.