0

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

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

2
  • "a json" … sorry, I laughed to myself Commented May 12, 2018 at 15:12
  • This question has been stripped of all its original context. In its current state it is not suitable anymore as SO posting. Commented Feb 22, 2020 at 23:00

3 Answers 3

1

You can simply loop through json in javascript like:

for(key in json){
    console.log(key,json[key]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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]);
}

Comments