foreach for JSON array , syntax

JavascriptJqueryJson

Javascript Problem Overview


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"));

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Try this:

$.each(result,function(index, value){
    console.log('My array has at position ' + index + ', this value: ' + value);
});

Solution 3 - Javascript

You can use the .forEach() method of JavaScript for looping through JSON.

var datesBooking = [
    {"date": "04\/24\/2018"},
      {"date": "04\/25\/2018"}
    ];
    
    datesBooking.forEach(function(data, index) {
      console.log(data);
    });

Solution 4 - Javascript

Sure, you can use JS's foreach.

for (var k in result) {
  something(result[k])
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavidView Question on Stackoverflow
Solution 1 - JavascripthvgotcodesView Answer on Stackoverflow
Solution 2 - JavascriptHari PachuveetilView Answer on Stackoverflow
Solution 3 - JavascriptyogihostingView Answer on Stackoverflow
Solution 4 - JavascriptTamzin BlakeView Answer on Stackoverflow