我的rest API返回以下json内容:
[{ "key": "apple", "value": "green" }, { "key": "banana", "value": "yellow" }]我正在使用以下代码遍历列表:
this.props.json.map(row => { return <RowRender key={id.row} row={row} /> }它可以工作,因为显示了内容,但是在Web浏览器的控制台上我看到一个错误:
地图不是函数
我用它搜索了一下,然后将代码更改为此:
Array.prototype.slice.call(this.props.json).map(row => { return <RowRender key={id.row} row={row} /> }它可以正常工作,但看起来很复杂.这是做这项工作的正确方法吗?
更新
我尝试过的事情:
- JSON.parse(...).map:JSON输入意外结束
- JSON.parse(JSON.stringify(...)).map(...):显示了数据,但出现错误:JSON.parse(...).map不是函数
- Array(...).map:数组或迭代器中的每个子代都应具有唯一的键.
this.props.json不是数组,它是类似数组的对象,而map是数组函数.解决此问题的方法是,使用.slice()将类似数组的对象转换为数组.
一种更优雅的方法:
Array.from(this.props.json).map(row => <RowRender key={id.row} row={row} />)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:
this.props.json.map(row => { 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:
Array.prototype.slice.call(this.props.json).map(row => { 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?
UPDATE
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.
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} />)
更多推荐
将json转换为数组/映射
发布评论