Oct 16, 2014

Looping Through A Jquery JSON Array

First we have to create the array and initialize in the place you would like it.
This is how we do it.
var owners = new Array();

Then we will have to write some data into the array.
Below i have used an example which stores  two  values into one single JSON object.

We use the keyword PUSH to store the data into the array.
owners.push({"Name": "Hudhaifa" , "Website": "www.easycodestuff.com"});

Lets push another object to the array.
owners.push({"Name": "Nifal" , "Website": "www.easycodestuff.com"});

Now the array would have two JSON Objects .One JSON object will have two values inside.
We can check the length if the object with the code below.

Object.keys(owners).length
How to empty the array ? So simple..
owners= [];
Now lets see how we can loop through this owners array and retrieve the data from the object
First we will need a .each array to loop through our array we have created.
We have to pass our array name as the first parameter to the .each loop as done below.
$.each( owners, function( key, value ) {
alert( key + ": " + value );
});
key -- >  Will return the loop number
value -- > value will return the a single object.
We will have to access our values like this -- > value.Name , value.Website
Let me give you the full .each loop to get the values and alert it.
$.each( owners, function( key, value ) {
alert( key + ": " + value.Name + " - " + value.Website ); //this will alert your array number and the values
});
Let me conclude by saying you will have to link the jquery lastest script to use these .each function
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Feel Free To Email Us If You Have Any Problem Regarding This.

No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...