Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach for JSON array , syntax

my script is getting some array from php server side script.

result = jQuery.parseJSON(result); 

now I want to check each variable of the array.

if (result.a!='') { something.... } if (result.b!='') { something.... } .... 

Is there any better way to make it quick like in php 'foreach' , 'while' or smth ?

UPDATE

This code ( thanks to hvgotcodes ) gives me values of variables inside the array but how can I get the names of variables also ?

for(var k in result) {    alert(result[k]); } 

UPDATE 2

This is how php side works

$json = json_encode(array("a" => "test", "b" => "test",  "c" => "test", "d" => "test")); 
like image 522
David Avatar asked Oct 05 '11 14:10

David


People also ask

Can I use forEach on JSON?

Sure, you can use JS's foreach.

How do you loop a JSON array?

To loop through a JSON array with JavaScript, we can use a for of loop. to loop through the json array with a for of loop. We assign the entry being looped through to obj . Then we get the value of the id property of the object in the loop and log it.

What is the correct way to write a JSON array?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.

Can you use forEach on an array?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.


2 Answers

You can do something like

for(var k in result) {    console.log(k, result[k]); } 

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object" 

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

like image 72
hvgotcodes Avatar answered Oct 12 '22 22:10

hvgotcodes


Try this:

$.each(result,function(index, value){     console.log('My array has at position ' + index + ', this value: ' + value); }); 
like image 43
Hari Pachuveetil Avatar answered Oct 12 '22 23:10

Hari Pachuveetil