首页 > 解决方案 > 地图搜索在数组内做出反应

问题描述

嘿,我在数据库中有这个表

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
      }
    }
  })
}

任何帮助,将不胜感激。

标签: javascriptarraysreactjs

解决方案


由于您的数据的组织方式,我建议先对其进行迭代,以便拥有更好的映射结构。

在此示例中,我假设您的数据从数据库中提取后如下所示。

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]}}
  }
}, {});

代码在做什么?

  1. 遍历数据中的每一项
  2. 如果此人在场,则将类中的值添加到对象中的数组中。
  3. 如果不是,则添加 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


推荐阅读