-3

I have a string like this:

var x = "[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]"

I expect to loop until end and read the id and text one by one, how to do this in javascript?

I have tried below:

var myArr = JSON.parse(x);
for (var i in myArr) {
     alert(myArr[i]);
}
FBDon
  • 23
  • 6
  • 1
    Did you try searching for how to iterate over an array in Javascript? That would be much faster than a SO post – Andy Ray Apr 14 '22 at 16:22
  • 3
    `var x = "[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]"` isn't valid JavaScript. Either use different outer quotes `var x = '[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]'` or escape the inner quotes `var x = "[{\"id\": \"40\", \"text\": \"Budi \"}, {\"id\": \"47\", \"text\": \"Staff 01\"}]"`. – jabaa Apr 14 '22 at 16:25
  • 2
    Does this answer your question? [For-each over an array in JavaScript](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – Jared Smith Apr 14 '22 at 16:26

1 Answers1

2

Your JavaScript is invalid. Make sure to wrap it in single quotes.

var x = '[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]'
var myArr = JSON.parse(x);
for (var i in myArr) {
     console.log("id: " + myArr[i].id);
     console.log("text: " + myArr[i].text);
}
Ahsan Ali
  • 4,951
  • 2
  • 17
  • 27