I have a JSON API that responds with a data structure for a single record, with an array of associations nested in the record. An example of the api response looks like this:
我有一个JSON API,它响应单个记录的数据结构,并在记录中嵌套了一组关联。 api响应的示例如下所示:
{
"name":"foo",
"bars":[
{
"name":"bar1"
},
{
"name":"bar2"
},
{
"name":"bar3"
}
]
}
I am trying to map the "bars" node to a react list of "paragraph" html tags, but I have had no success. I tried using "Object.keys.map" as seen here and here but I still couldn't get the data transformation right.
我试图将“bars”节点映射到“paragraph”html标签的反应列表,但我没有成功。我尝试使用“Object.keys.map”,如此处和此处所示,但我仍然无法正确地进行数据转换。
I'm new to react/js so not sure how to achieve this.
我是新的反应/ js所以不知道如何实现这一点。
3 个解决方案
#1
0
Imagine your JSON data is saved to an attribute named record
.
想象一下,您的JSON数据将保存到名为record的属性中。
const RecordItem = ({
record
}) => (
<div>
{record.bars.map((bar, index) => (
<p key={index}>{bar.name}</p>
)}
</div>
)
// Then, put this wherever:
<RecordItem record={record} />
Should do the trick! Obviously, modify to suit your needs.
应该做的伎俩!显然,修改以满足您的需求。
#2
0
bars
in response is array - iterate it directly. Array provides map
method to do so.
响应中的条是数组 - 直接迭代它。 Array提供了map方法。
render() {
return (
<div>
{response.bars.map((item, idx) => (
<p key={idx}>{item.name}</p>
))}
</div>
)
}
Note: response
is data received from API
注意:响应是从API接收的数据
#3
0
// get the <p> virtual DOM element
const { p } = React.DOM
// Your data mapped into the <p> element
// ps :: [ React.DOM ]
const ps = YourObj.bars.map((b, i) => p({key: i}, b.name))
//~> [ <p>bar1</p>, <p>bar2</p>, <p>bar3</p> ]
Now you can use ps
wherever you please.
现在你可以随时随地使用ps。
#1
0
Imagine your JSON data is saved to an attribute named record
.
想象一下,您的JSON数据将保存到名为record的属性中。
const RecordItem = ({
record
}) => (
<div>
{record.bars.map((bar, index) => (
<p key={index}>{bar.name}</p>
)}
</div>
)
// Then, put this wherever:
<RecordItem record={record} />
Should do the trick! Obviously, modify to suit your needs.
应该做的伎俩!显然,修改以满足您的需求。
#2
0
bars
in response is array - iterate it directly. Array provides map
method to do so.
响应中的条是数组 - 直接迭代它。 Array提供了map方法。
render() {
return (
<div>
{response.bars.map((item, idx) => (
<p key={idx}>{item.name}</p>
))}
</div>
)
}
Note: response
is data received from API
注意:响应是从API接收的数据
#3
0
// get the <p> virtual DOM element
const { p } = React.DOM
// Your data mapped into the <p> element
// ps :: [ React.DOM ]
const ps = YourObj.bars.map((b, i) => p({key: i}, b.name))
//~> [ <p>bar1</p>, <p>bar2</p>, <p>bar3</p> ]
Now you can use ps
wherever you please.
现在你可以随时随地使用ps。