2

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?

Suhas Bhattu
  • 539
  • 4
  • 17

1 Answers1

2

This is how you can access the data from the JSON, no need to use paths:

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"
        }
    ]
}

var age = data.age;
var cityPath = data.address.city;
var faxNumber = data.phoneNumber[0].number; // array first item begins with 0

console.log({age, cityPath, faxNumber})

If you really need to use paths for some reason, I suggest using lodash get method https://lodash.com/docs#get

rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63