[英]Rendering an Array of Data with map() and JSX to [[]]
I have a function in JSX
that stores value gotten from a database
thus:我在JSX
中有一个函数可以存储从database
值,因此:
const data = JSON.parse(xhr.responseText);
this.setState({ data: data });
The response format is:响应格式为:
[{"id":4,"name":"Avengers: Infinity War","year":2018},{"id":5,"name":"Thor: Ragnarock","year":2017},{"id":6,"name":"Black Panther","year":2018},{"id":7,"name":"Star Wars: The Rise of Skywalker","year":2019}]
However, I am trying to use a react
table control
that expects the data to be in this format:但是,我正在尝试使用期望数据采用以下格式的react
table control
:
const data = [
['1st column', '2nd column', '3rd column'],
['1st cell', '2nd cell', '3rd cell']
]
render() {
<ReactTabllist
data={data}
property={property} />
}
So I need to turn the JSON
into an javascript
array
of arrays.所以我需要将JSON
转换为一个javascript
array
数组。 What is a good way to do this?有什么好的方法可以做到这一点?
const data = this.state.data.map(movie => ( /* what goes here? */ ));
As per I understand, you need to get every property in the JSON and then put the values of every element into the data
-react property.据我了解,您需要获取 JSON 中的每个属性,然后将每个元素的值放入data
-react 属性中。
So, first you would need to make sure, the response from the database is well formatted, and that every element in the json-parsed responseText
is the same as the rest of them.因此,首先您需要确保来自数据库的响应格式正确,并且 json 解析的responseText
中的每个元素都与其余元素相同。
With that into account:考虑到这一点:
const formattedData = this
.state
.data
.map(movie => Object.keys(movie).map(key => movie[key]));
And that formattedData
is what you want to pass as react-attribute of data={formattedData}
而那个formattedData
就是你想要作为data={formattedData}
react-attribute 传递的
Alternatively, if you don't care about the keys of the movie whatsoever, you could do as @Madmadi has suggested:或者,如果您根本不关心电影的键,您可以按照@Madmadi 的建议进行操作:
const formattedData = this
.state
.data
.map(movie => Object.values(movie));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.