Categories
JavaScript Answers

How to loop through a JSON array with JavaScript?

Spread the love

Sometimes, we want to loop through a JSON array with JavaScript.

In this article, we’ll look at how to loop through a JSON array with JavaScript.

How to loop through a JSON array with JavaScript?

To loop through a JSON array with JavaScript, we can use a for of loop.

For instance, we write

const json = [
  {
    id: "1",
    msg: "hi",
    tid: "2022-05-05 23:35",
    fromWho: "hello1@email.cpm",
  },
  {
    id: "2",
    msg: "there",
    tid: "2022-05-05 23:45",
    fromWho: "hello2@email.cpm",
  },
];

for (const obj of json) {
  console.log(obj.id);
}

to loop through the json array with a for of loop.

We assign the entry being looped through to obj.

Then we get the value of the id property of the object in the loop and log it.

Conclusion

To loop through a JSON array with JavaScript, we can use a for of loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *