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"));
Sure, you can use JS's foreach.
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.
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.
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.
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.
Try this:
$.each(result,function(index, value){ console.log('My array has at position ' + index + ', this value: ' + value); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With