我在React工作,我有以下数据结构,我试图为选择下拉组件生成选项,包括用于打包三组团队成员的OptGroups使用地图和ES6箭头功能。
"teams": [
{
"Group A":
[
{ "id": "A1", "name": "John" },
{ "id": "A2", "name": "Erin" },
{ "id": "A3", "name": "Steve" }
],
"Group B":
[
{ "id": "B1", "name": "Mark" },
{ "id": "B2", "name": "Doug" },
{ "id": "B3", "name": "Sam" },
{ "id": "B4", "name": "Kate" }
],
"Group C":
[
{ "id": "C1", "name": "Michelle" },
{ "id": "C2", "name": "April" },
{ "id": "C3", "name": "Mike" },
{ "id": "C4", "name": "Albert" }
]
}
]
在JSON与团队分组嵌套之前,我一直在使用这种语法:
let teamOptions = this.props.firm.teams.map(memb => <Option key={memb.id}>{memb.name}</Option>);
既然我已经将团队成员嵌入到组中,我就无法找到正确的方法来处理这个问题。
我希望输出类似:
<OptGroup label="Group A">
<Option value="A1">John</Option>
<Option value="A2">Erin</Option>
<Option value="A3">Erin</Option>
</OptGroup>
<OptGroup label="Group B">
<Option value="B1">Mark</Option>
<Option value="B2">Doug</Option>
<Option value="B3">Sam</Option>
<Option value="B4">Kate</Option>
</OptGroup>
<OptGroup label="Group C">
<Option value="C1">Michelle</Option>
<Option value="C2">April</Option>
<Option value="C3">Mike</Option>
<Option value="C4">Albert</Option>
</OptGroup>
答案 0 :(得分:1)
正如@Bergi所提到的,有点不清楚你在示例数组中提供的结构是否有一个对象,而不是像这样的格式:
"teams": [
{
"name": "Group A",
"players": [
{ "id": "A1", "name": "John" },
{ "id": "A2", "name": "Erin" },
{ "id": "A3", "name": "Steve" }
]
},
{
"name": "Group B",
"players": [
{ "id": "B1", "name": "Mark" },
{ "id": "B2", "name": "Doug" },
{ "id": "B3", "name": "Sam" },
{ "id": "B4", "name": "Kate" }
]
},
]
但无论如何,为了回答你关于如何映射它的问题,我会这样做:请注意你的数组有一个对象,所以我抓住你的团队数组中的第一项,然后迭代键/值。鉴于你想迭代第一个对象,我就是这样做的:
const keys = Object.keys(this.props.firm.teams[0]);
const values = Object.values(this.props.firm.teams[0]);
const teamOptions = values.map((group, i) => {
<OptGroup label={keys[i]} />
{ group.map(player => <Option value={player.id}>{player.name}</Option>) }
</OptGroup>
});