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"));
This question is related to
javascript
jquery
json
You can use the .forEach() method of JavaScript for looping through JSON.
var datesBooking = [_x000D_
{"date": "04\/24\/2018"},_x000D_
{"date": "04\/25\/2018"}_x000D_
];_x000D_
_x000D_
datesBooking.forEach(function(data, index) {_x000D_
console.log(data);_x000D_
});
_x000D_
Try this:
$.each(result,function(index, value){
console.log('My array has at position ' + index + ', this value: ' + value);
});
Sure, you can use JS's foreach.
for (var k in result) {
something(result[k])
}
Source: Stackoverflow.com