nextjs for loop json

nextjs

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()
      setData(json)
    }
    loadData()
  }, [])

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

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

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.