nextjs for loop json


To loop through a JSON object in a Next.js component, you can use the Object.keys() function to get an array of the object’s keys, and then use the map() function to iterate over the array.

Here’s an example of how you can do this:

import { useEffect, useState } from 'react'

function MyComponent() {
  const [data, setData] = useState(null)

  useEffect(() => {
    async function loadData() {
      const res = await fetch('/data.json')
      const json = await res.json()
  }, [])

  if (data === null) {
    return <p>Loading data...</p>

  return (
      {Object.keys(data).map(key => (
        <li key={key}>
          {key}: {data[key]}

export default MyComponent

In this example, the Object.keys() function is used to get an array of the keys in the data object, and the map() function is used to iterate over the array and render a list item for each key-value pair.

Keep in mind that the data object should be a JSON object with key-value pairs. If the object is an array of objects, you’ll need to use a different approach to loop through the array.