user1184100
user1184100

Reputation: 6894

How to loop through an array that is nested within an object?

I'm trying to get the contents of data within the subject array using jquery. How can this be done ? I tried using $.each but couldn't get the contents .

  "student": {
    "name": "sdfdsf",
    "age": 3,
    "subject": [
        {
            "science": "dfsdfdfd",
            "book": "sdfds"
        },
        {
            "math": "vbcb",
            "book": "sdfds"
        }
    ]
}

Upvotes: 0

Views: 299

Answers (3)

Umesh Patil
Umesh Patil

Reputation: 10685

Given JSON (Lets's call it info here) is an object with nodes name, age, subject. And Subject is an Array of JSONs containing name and book key-value pairs.

Here, you need to access the subject node first, which is an array and iterate the array to get the each subect. Key value pair can be accessed again at each array element.

Below is the source code for iterating the content.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
var info={"student": {
    "name": "Tom",
    "age": 3,
    "subject": [
        {
            "science": "scscsc",
            "book": "SciBook"
        },
        {
            "maths": "mmmm",
            "book": "MathBook"
        },
        {
            "History": "hshshs",
            "book": "hisBook"
        }
]
}};
    var subjects=info["student"]["subject"];
    //Iterate all the subejcts present in the subject Node

    for(i=0;i<subjects.length;i++){
    // Get the information of particular subejct
        $.each(subjects[i],function(key,val){
           alert(i+"> Sub[ "+key+" ]="+val);
        })
    }
 });
</script>
</head>
<body>
</body>
</html>

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

To use $.each on an array:

$.each( student.subject, function ( arrayIndex, arrayItem){
     console.log( arrayItem.science);
});

Upvotes: 0

maxedison
maxedison

Reputation: 17553

Not sure what problem you ran into, but the following will loop over the array in question:

for(var i = 0; i < student.subject.length; i++){
    //student.subject[i] refers to the current item in the array
}

You would generally use $.each() to loop over an object's properties. In this case, you are simply looping over an array.

Upvotes: 2

Related Questions