javascript - 地图搜索在数组内做出反应
问题描述
嘿,我在数据库中有这个表
st_ID firstName LastName Classes
1 paul adams php
1 paul adams javascript
1 paul adams ASP
2 Georges wayne PHP
所以我想要这个结果:
<table>
<thead>
<tr>
<td>FirstName</td>
<td>LastName</td>
<td>Classes</td>
</tr>
</thead>
<tbody>
<tr>
<td>paul</td>
<td>adams</td>
<td>php, javascript,Asp</td>
</tr>
</tbody>
<table>
所以我使用了反应中的地图功能
renderTable(testValue) {
let arrayValue = [];
let arrayID = '';
map(testValue, (x) => {
if (!arrayID){
arrayID = x.st_ID
}
else{
if (arrayID === x.st_ID){
// here iw ant to show all classes with same st_ID
}
else{
// here i want to show classes of next st_ID
}
}
})
}
任何帮助,将不胜感激。
解决方案
由于您的数据的组织方式,我建议先对其进行迭代,以便拥有更好的映射结构。
在此示例中,我假设您的数据从数据库中提取后如下所示。
const databaseData = [
{
st_ID: 1,
firstName: 'paul',
lastName: 'adams',
classes: 'php'
}, {
st_ID: 1,
firstName: 'paul',
lastName: 'adams',
classes: 'JS'
}
]
第一次迭代:将每个技能分配给个人。实现此目的的一种方法是使用.reduce数组函数。
const combineClasses = data.reduce((collect, {st_ID, firstName, lastName, classes}) => {
if (collect[st_ID]) {
classes = [...collect[st_ID].classes, classes]
return {...collect, [st_ID]: {...collect[st_ID], classes}}
} else {
return {...collect, [st_ID]: {firstName, lastName, classes: [classes]}}
}
}, {});
代码在做什么?
- 遍历数据中的每一项
- 如果此人在场,则将类中的值添加到对象中的数组中。
- 如果不是,则添加 id 作为对象中的键,并添加名字、姓氏和类(在数组中)。
第二次迭代:现在您已经整理好数据并列出了每个人的技能,映射起来会容易得多。例如。
<tbody>
{ Object.keys(combineClasses).map((key) => {
return (
<tr>
<td>{combineClasses[key].firstName}</td>
<td>{combineClasses[key].lastName}</td>
<td>{combineClasses[key].classes.join(', ')}</td>
</tr>
);
})}
</tbody>
显然,您需要代码来显示完整的表格并包含标题。您将在下面找到一个工作示例。 https://codepen.io/roycode/pen/vaGoGR?editors=0010
推荐阅读
- android - 将我的 Unity android 升级到 64 位后,在 Google Play 上上传 apk 后仍然出现错误。不符合 64 位
- javascript - 我的 Json 数组只返回最后一个数组。如何解决?
- python - 如何在 Bokeh 中添加多行 x 轴标签?
- node.js - 使用 NodeJS 从服务器下载大量图像(> 2GB)
- couchdb - 基于动态选择器查询搜索沙发数据库
- laravel - Laravel - 使用 Response::make 查看 pdf 文件时设置页面标题
- docker - 撰写文件似乎未读
- opencv - 如何访问 Google Colaboratory 中的工作目录?
- mysql - Docker - 为另一个应用程序使用相同的网络和数据库?
- gnuplot - 填充透明图中的xrange问题