javascript - 如何迭代数据组并以列表形式返回
问题描述
我有这样的数据
0: {rowid: "4b531532a5a9", groups: "Group1", descriptions: "Item1"......}
1: {rowid: "e55315ccabb5", groups: "Group2", descriptions: "Item2"......}
2: {rowid: "f27135283089", groups: "Group1", descriptions: "Item3"......}
我需要像这样展示它https://codesandbox.io/s/material-demo-fwi6f?file=/demo.js
所以首先,当我从 API 获取数据时,首先我在下面做(groupBy 是一个 lodash 方法,它通过数据和按属性分组)
let list = groupBy(response.data, "groups");
this.setState({
Groups: Object.keys(list),
BackOffice: response.data,
});
这样我就可以将所有组名和数据保存到状态中。然后我到目前为止有下面的代码来创建一个完整的列表,但我不确定为什么它不起作用..
GetBackOffice = () => {
return (
<Grid item xs={12}>
<List dense style={{ padding: 0, margin: 0 }}>
{this.GetList()}
</List>
</Grid>
);
};
GetList = () => {
let list = "";
this.state.Groups &&
this.state.Groups.map((EachGroup) => {
let CurrentData = this.state.BackOffice.filter(
(row) => row.groups === EachGroup
);
list += CurrentData.map((row) => (
<ListItem>
<ListItemText primary="1" />
<ListItemSecondaryAction>
<IconButton edge="end" aria-label={row.descriptions}>
<DownloadIcon />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
));
});
return list;
};
解决方案
https://codesandbox.io/s/material-demo-w5dl3
在映射的同时
使用flatMap来展平数组
GetList = () =>
this.state.Groups &&
this.state.Groups.flatMap(EachGroup => {
let CurrentData = this.state.BackOffice.filter(
row => row.groups === EachGroup
);
return CurrentData.map(row => (
<ListItem>
<ListItemText primary="1" />
<ListItemSecondaryAction>
<IconButton edge="end" aria-label={row.descriptions}>
<DownloadIcon />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
));
});
https://codesandbox.io/s/material-demo-x7edo
我建议直接将 groupBy 返回的对象与Object.values()(或 Object.entries())一起使用,而不是每次都按键过滤:
GetData = () => {
const Groups = groupBy(response.data, "groups");
this.setState({
Groups
});
};
GetList = () =>
this.state.Groups &&
Object.values(this.state.Groups).map(CurrentData => {
return CurrentData.map(row => (
<ListItem key={row.rowid}>
<ListItemText primary="1" />
<ListItemSecondaryAction>
<IconButton edge="end" aria-label={row.descriptions}>
<DownloadIcon />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
));
});
推荐阅读
- javascript - 为什么这个 json 检索代码不起作用?
- python - 写入 GML 文件时出现 NetworkX 密钥错误
- android - Android单元测试中的资源文件访问“InvocationTargetException”
- python - 考虑顺序对 pandas 列执行累积计数
- html - Firefox 忽略最小宽度和最大宽度的图像尺寸属性
- c++ - 基本形状识别(openCV C++)
- c# - ASP.NET Core:调用之间的空闲超时有延迟
- c++ - 在模板元编程中使用列表类型
- c# - 从另一个线程调用时不会触发操作
- c# - 在 asp.net 网络表单中注册后,如何通过电子邮件从 sql 数据库向用户发送自动生成的 ID