如何使用.filter()从数组中删除值?

时间:2019-11-02 19:40:04

标签: javascript reactjs

我正在为游戏排行榜。我正在使用的userInfo数组包含从json表中提取的数据。该数组包含idusernamebestattemptsbesttime以及每个类别的数据。

该表当前有4列,并且json表中的所有数据都在表行中。我需要使该表不显示具有bestattemps < 5besttime === 0的用户的数据。我正在尝试从数组中过滤数据,但无法正常工作,并且出现以下错误:TypeError: Cannot convert undefined or null to object在此行const keys = Object.keys(newArray[0])

代码如下:

import React from "react";
import "./LeaderBoard.css";


const Head = ({keys, head}) => {
  return (
    <thead>
      <tr>
    {
      keys.map(key =><th key={key}>{head[key] || key}</th> )
    }
    </tr>
  </thead>

  )
}
const Row = ({row}) => {
  const keys = Object.keys(row)

  return (

  <tr key={row.Rank}>
    {
      keys.map(key => <td key={key}>{row[key]}</td>)

    }

 </tr> )
}
  const LeaderBoard = ({usersInfo, head}) => {

    usersInfo.sort(function sortByAttempts(a, b) {
      if(a.bestattempts !== b.bestattempts){
        return a.bestattempts - b.bestattempts
      }else{
        return a.besttime - b.besttime
      }

  });

const newArray = usersInfo.map(({ id, ...rest }, index) => ({ Rank: index + 1, ...rest }) )

  const keys = Object.keys(newArray[0])

  const filteredData = newArray.filter(usersInfo => usersInfo.bestattempts >= 5 && usersInfo.besttime !== 0);



  return (
  <div className="Leaderboard-wrapper">
  <table>
    <Head keys={keys} head={head}/>
    <tbody>
      {
        filteredData.map((row) => <Row row={row}/>)
      }
    </tbody>
  </table></div>
)
};

export default LeaderBoard;

在app.js上作为道具

 const head = {
                id: "ID",
                username: "Username",
                bestattempts: "Best Attempts",
                besttime: "Best Time",
            }

1 个答案:

答案 0 :(得分:1)

您可能想对标题进行硬编码。与其依赖过滤器中的数据(可能会导致空数组并因此导致array[0]抛出),不如考虑对标头进行硬编码。小变化,例如const keys = ['Rank', 'username', 'bestattempts', 'besttime'].

最终,您还将希望标头值不依赖于描述对象的键。我还建议更改Row的实现,而不是对所有键进行循环,而是确定要返回它们的顺序。

<td>{row['Rank']}</td>
<td>{row['username']}</td>
<td>{row['bestattempts']}</td>
<td>{row['besttime']}</td>

这样,您可以完全控制值的顺序。