将json转换为数组/映射

编程入门 行业动态 更新时间:2024-10-28 12:27:06
本文介绍了将json转换为数组/映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的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转换为数组/映射

本文发布于:2023-10-28 23:01:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!