Gus
Gus

Reputation: 943

Jquery read value of json nested object

I'm trying to read the value of a json nested object.
I have tried in these ways but without success.

data

{ "foo":  1,
  "bar": 10,
  "rows": [ {"id":1,"name":"Luke" },
            {"id":2,"name":"Sky" },
            {"id":3,"name":"Walker"} ]
}

Ajax

$.ajax({
    data: params,
    dataType: 'json',
    success: function(data) {

        console.log(data.rows) // data of rows object - OK !
        console.log(data["rows"].id); // undefined
        console.log(data.rows.id); // undefined
    }
});

How could I do? Thank you

Upvotes: 2

Views: 1864

Answers (2)

Shubham Nigam
Shubham Nigam

Reputation: 3944

Data.rows is array of objects It should be accessed in other way

 $.ajax({
        data: params,
        dataType: 'json',
        success: function(data) {

            console.log(data.rows) // data of rows object - OK !
          $.each( data.rows, function( key, value ) {
      console.log( key + ": " + value );
       });

        }
    });

Upvotes: 1

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

Rows is an array.

Change

console.log(data["rows"].id);

to

console.log(data["rows"][0].id);

You can also iterate on it to get all the values

for (var i = 0; i < data["rows"].length; i++) {
    console.log(data["rows"][i].id); 
}

Upvotes: 2

Related Questions