Shubham Kanodia
Shubham Kanodia

Reputation: 6236

How to fetch object names while parsing JSON

Say my json looks like this :

{
    "Heading1":{"internal 1":[0,0,0,1],"internal 2":[0,0,0,0]},
    "Heading2":{"internal 1":[0,0,0,0],"internal 2":[0,0,0,0]}
}

I wrote the following jquery function

$.each(jsonData, function(index, data){
        console.log(data);
    });

But this only gives me the separate objects as such:

{"internal 1":[0,0,0,1],"internal 2":[0,0,0,0]}

and

{"internal 1":[0,0,0,0],"internal 2":[0,0,0,0]}

But how do i fetch the "Heading" (i.e the object name) for each ? is there an inbulit attribute? like say data.name or data.id or something?

Upvotes: 1

Views: 56

Answers (1)

tymeJV
tymeJV

Reputation: 104795

Using $.each, the index property you defined is actually the key:

$.each(jsonData, function(key, value){
    console.log(key) //Heading1
})

Or, for in

for (var key in jsonData) {
    console.log(key) //Heading1
    console.log(jsonData[key]) //{"internal 1":[0,0,0,1],"internal 2":[0,0,0,0]}
}

Upvotes: 2

Related Questions