user999491 user999491 - 7 months ago 40
Javascript Question

How to access nested JSON data

Let say I have json data like

data = {"id":1,
"address": {"streetName":"cde",

Now I am getting fields to be accessed from this json data like :
fields = ["id", "name", "address.streetName"]

How could I access third field (
) from given json data in most efficient way?
doesn't work

One possibility is I construct
string using a for loop and do eval of that but is there any efficient way of doing this?


To be honest, I can't understand your problem. JSON is already structured out, why do you need to change the structure?

In you case, I would access it as follows:


If, by any chance, what you want is to traverse the data, you would need:

function traverse_it(obj){
    for(var prop in obj){
        if(typeof obj[prop]=='object'){
            // object
            // something else
            alert('The value of '+prop+' is '+obj[prop]+'.');



After reading below, what this user needs seems more obvious. Given property names as a string, s/he wants to access the object.

function findProp(obj, prop, defval){
    if (typeof defval == 'undefined') defval = null;
    prop = prop.split('.');
    for (var i = 0; i < prop.length; i++) {
        if(typeof obj[prop[i]] == 'undefined')
            return defval;
        obj = obj[prop[i]];
    return obj;

var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
var props = 'address.streetName';
alert('The value of ' + props + ' is ' + findProp(data, props));