zappee zappee - 10 months ago 131
Javascript Question

convert json to array/map

My rest API returns with the following json content:

"key": "apple",
"value": "green"
"key": "banana",
"value": "yellow"

I am iterating through the list with this code: => {
return <RowRender key={id.row} row={row} />

It works because the content is displayed but on the web browser's console I can see an error:

map is not a function

I googled for it and I changed my code to this: => {
return <RowRender key={id.row} row={row} />

It works without any error but seems so complicated. Is that the correct way to do this job?


What I tried:

  • JSON.parse(...).map: Unexpected end of JSON input

  • JSON.parse(JSON.stringify(...)).map(...): data is displayed but I get an error: JSON.parse(...).map is not a function

  • Array(...).map: Each child in array or iterator should have a unique key.

Answer Source

in your code this.props.json is not an array, it's an array-like object and map is an array function. what your doing to solve this, is converting that array-like object into an array, with .slice()

a more elegant way to do this:

Array.from(this.props.json).map(row => <RowRender key={id.row} row={row} />)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download