Suppose I have a JSON Object like this:
var data = {
"name": "abcd",
"age": 21,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
and I want to get the information from this json object by using path which is a string, like
var age = 'data/age'; // this path should return age
var cityPath = 'data/address/city'; // this path should return city
var faxNumber = 'data/phoneNumber/1/number'; // this path should return fax number
Is there any way I can get this information from the string path? Currently I am splitting the path by /
and then using it like data.age
or data.address.city
. But this approach is not useful for any array contained in JSON object.
Is there any better and optimal approach in JavaScript for this problem?