user9646331
user9646331

Reputation:

How to loop through a json in javascript?

I'm trying to do this PHP equivalent in javascript.

How can I do the same loop I did with PHP in javascript?

Upvotes: 0

Views: 60

Answers (3)

CodeF0x
CodeF0x

Reputation: 2682

To loop through JSON in JavaScript, use a for ... in ... loop like this:

var json = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

for (key in json) {
  console.log(key + ": " + json[key]);
}

Upvotes: 0

YoYo
YoYo

Reputation: 9405

You got the basic syntax of looping wrong:

  for (json.messages in object){
    alert(object.message);
  }

Assuming that you want to loop the messages in json.messages, and using a name other than object as that might be a system built-in, you would actually write it as follows:

  for (alertMessage in json.messages){
    alert(alertMessage);
  }

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

you got basically the position of variable and array wrong: variable comes left side of the in.

Upvotes: 0

sourabh
sourabh

Reputation: 48

You can simply loop through json in javascript like:

for(key in json){
    console.log(key,json[key]);
}

Upvotes: 1

Related Questions