[javascript] 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"));

This question is related to javascript jquery json

The answer is


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

_x000D_
_x000D_
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_
_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])
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?