gpt4 book ai didi

javascript - 如果数组位于使用 map 方法的对象中,如何从数组中获取数据?

转载 作者:行者123 更新时间:2023-11-30 10:59:15 25 4
gpt4 key购买 nike

有 Api - 一个数组:

[
{"id":1,"firstName":"Alex","lastName":"Creel","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":2,"firstName":"Todd","lastName":"Drek","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":3,"firstName":"Jim","lastName":"Sparou","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":4,"firstName":"Tom","lastName":"Limls","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":5,"firstName":"Jack","lastName":"Retnd","email":"BGibson@placerat.ly","phone":"(898)979-8452"}
]

使用fetch,我得到了Api——一个变成数据对象的数组(我没有写App.js代码,所以问题不会太长)并使用 map 方法,以表格的形式,在页面上显示我需要的数据:

export default props => (
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
{props.data.map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.firstName}</td>
<td>{item.lastName}</td>
</tr>
))}
</tbody>
</table>
)

屏幕上会出现这样一个表格:
enter image description here
但是我有第二个奇怪的 Api:

{"group":{"first":[
{"id":1,"firstName":"Alex","lastName":"Creel","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":2,"firstName":"Todd","lastName":"Drek","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":3,"firstName":"Jim","lastName":"Sparou","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":4,"firstName":"Tom","lastName":"Limls","email":"BGibson@placerat.ly","phone":"(898)979-8452"},
{"id":5,"firstName":"Jack","lastName":"Retnd","email":"BGibson@placerat.ly","phone":"(898)979-8452"}
]}}

我有一个问题,我该如何更改这部分代码:

{props.data.map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.firstName}</td>
<td>{item.lastName}</td>
</tr>

如何使 map 方法与屏幕上的第二个 api 一起工作,并获得与第一个 api 完全相同的名称列表?
我试过这样:

{props.data.group.first.map(item =>

但是接着报错:类型错误:无法读取未定义的“第一”属性

最佳答案

如果您尝试同时考虑这两种情况,也许您可​​以在映射项目之前快速检查一下,看看您当前使用的是哪种情况。例如:

const arr = props.data.group && props.data.group.first ? 
props.data.group.first : props.data;

arr.map(item => { ... });

关于javascript - 如果数组位于使用 map 方法的对象中,如何从数组中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com