1

I am using nextjs, React and Typescript. I want to loop out values from an array of objects. My

data.json:

[
    {
      "id": "value”,
      “name": “value”, 
      “type”: “value”
    },
    {
      "id": “value”,
      “name": “value”, 
      “type": “value”
    }
]

cars.map is not a function.

4
  • I didn't understand what stops you from iterate over the cars array. Why can't you do something like cars.map(car => Object.keys(car) ...)? Commented Dec 15, 2021 at 21:57
  • I get the data but mapping it gives ".map is not a function" Commented Dec 15, 2021 at 23:06
  • 2
    Ok, so maybe you need to do JSON.parse(cars) then you should have a real array. Commented Dec 16, 2021 at 9:09
  • as easy as that thanks! Commented Dec 16, 2021 at 9:15

1 Answer 1

1

Everything in your code appears to be properly typed. If you want to display values from your Cars array, you could map over the cars array, similarly to:

const IndexPage: NextPage<{ cars: Cars[] }> = ({ cars }) => {
  return (
    <div>
      <h1>IndexPage</h1>
      {cars.map(car => <div key={car.id}>{car.name}: {car.type}</div>)}
    </div>
  )
}

An array of React JSX generated by a map function need to have unique keys added on the parent tag of the map output. See Lists and Keys for more detail. For more detail on Map, see Array.prototype.map()

Sign up to request clarification or add additional context in comments.

5 Comments

{cars} shows me the data but cars.map gives undefined
When you say cars shows you the data, what variable type is it? If cars is truly an array, cars.map would not be undefined. Be sure you are copying the code as-is above, not wrapping the <div> with the car values in curly brackets.
typeof(cars) is a string!
JSON.parse(cars) should give you an JSON array you need.
amazing thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.