json - 在反应中将其从 csv 转换为 json 后,根据字段对 Json 数据进行分组
问题描述
在我的 react 应用程序中,我将 csv 文件转换为 JSON 对象,以便可以在 UI 的表格中显示它。但我想根据某个字段“IP 地址”对 JSON 数据进行分组。所有区域都应归入“AreaList”字段,该字段是原始“区域”字段的数组。
这是我将 csv 解析为 json 的源代码:
React.useEffect(() => {
Papa.parse(csvFile, {
download: true,
header: true,
skipEmptyLines: true,
complete: data => {
console.log(data.data);
}
});
}, []);
以下是上述代码的控制台日志输出:
[
{
IP Address: "192.168.0.1:61000",
area: "JA1_JA2", job: "test",
flow: "PartsServe",
Component: "1",
…
},
{
IP Address: "192.168.0.1:61000",
area: "JA1_JA2",
job: "test1",
flow: "PartsServe",
Component: "1",
…
},
{
IP Address: "192.168.0.1:63000",
area: "JA1_JA2",
job: "test",
flow: "PartsServe",
Component: "1",
…
},
{
IP Address: "192.168.0.1:63000",
area: "JA1_JA3",
job: "test2",
flow: "PartsServe",
Component: "1",
…
}
]
我想根据 IP 地址字段对 json 进行分组。生成的 json 应如下所示:
projects: [
{
IP Address: "192.168.0.1:61000",
AreaList: [
{
area: "JA1_JA2",
jobList: [
{job: "test", flow: "PartsServe", Component: "1"},
{job: "test1", flow: "PartsServe", Component: "1"}
]
},
]
},
{
IP Address: "192.168.0.1:63000",
AreaList: [
{
area: "JA1_JA2",
jobList: [
{job: "test", flow: "PartsServe", Component: "1"},
{job: "test1", flow: "PartsServe", Component: "1"}
]
},
{
area: "JA1_JA3",
jobList: [
{job: "test", flow: "PartsServe", Component: "1"},
{job: "test2", flow: "PartsServe", Component: "1"}
]
},
]
}
]
解决方案
我可以为你形成逻辑。可能不是优化的方式,但我很快就做到了。
const data = [
{
"IP Address": "192.168.0.1:61000",
area: "JA1_JA2", job: "test",
flow: "PartsServe",
Component: "1",
},
{
"IP Address": "192.168.0.1:61000",
area: "JA1_JA2",
job: "test1",
flow: "PartsServe",
Component: "1",
},
{
"IP Address": "192.168.0.1:63000",
area: "JA1_JA2",
job: "test",
flow: "PartsServe",
Component: "1",
},
{
"IP Address": "192.168.0.1:63000",
area: "JA1_JA3",
job: "test2",
flow: "PartsServe",
Component: "1",
}
];
const uniqueIPs = Array.from(new Set(data.map((item) => item["IP Address"])));
const areaList = uniqueIPs.map((ip) => {
const currentIpData = data.filter((item) => item["IP Address"] === ip);
const uniqueAreas = Array.from(new Set(currentIpData.map((item) => item.area)));
return ({
"IP Address": ip,
AreaList: currentIpData.map((area) => {
const currentJobData = currentIpData.filter((item) => item.area === area.area);
const uniqueJobs = Array.from(new Set(currentJobData.map((item) => item.job)));
return ({
area: area.area,
jobList: currentJobData.map((item) => ({
job: item.job,
flow: item.flow,
Component: item.Component
}))
})
})
})
})
console.log(areaList);
推荐阅读
- python - 创建平滑的跳跃动画
- laravel - 通过 mailgun 发送电子邮件时,此路由不支持 GET 方法
- javascript - 如何使网站按价格从大到小排序
- python - ImportError:无法从“预处理”导入名称“inception_preprocessing”
- pagination - 对集合使用分页时出现 Jekyll 布局错误 (jekyll-paginate-v2)
- json - 尝试通过 Compass 将 JSON 文件导入 MongoDB 时出现错误
- django - 为什么变量不能与 Django 信号中的“实例”一起使用?
- nginx - nginx 总是在域后添加斜杠
- reactjs - 反应返回组件onclick
- javascript - 如何使用正则表达式从不和谐消息中获取命令和参数,最后是(可选)用户