81

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"));
1
  • If i'm not mistaken, you can access the attributes of each JSON Object by using it's name, like you would a property. e.g. JSONObject.name to get the attribute inside JSONObject that holds {'name':'foo'} Commented Dec 27, 2016 at 19:10

4 Answers 4

144

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.

Sign up to request clarification or add additional context in comments.

5 Comments

you're going to want to square-bracket that. Edit: you fixed it.
yeah i actually made sure by trying in the console. ;)
that works. but 1 more problem, how can I get the names of those variables inside array ?
@david, is it an array, or an object literal?
@david, updated the answer -- k is the key, result[k] is the value.
38

Try this:

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

Comments

16

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

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

Comments

12

Sure, you can use JS's foreach.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.