在js中按用户角色过滤

Filtering by user role in js

我关注code

    export default function App() {
      const users = [
    { id: 34, name: "A", role: "pro" },
    { id: 43, name: "B", role: "customer" },
    { id: 35, name: "C", role: "pro" },
    { id: 55, name: "D", role: "pro" },
    { id: 67, name: "test", role: "pro" },
    { id: 543, name: "Jhon", role: "customer" }
     ];

     const customer = users.filter((u) => {
      return u.role === "customer";
     });

     const pro = users.filter((u) => {
    return u.role === "pro";
     });

    return (
    <div className="App">
      <Card role={"Customer"} count={customer.length} />
      <Card role={"Pro"} count={pro.length} />
    </div>
    );
    }

我正在尝试按角色过滤用户,然后我在 Card 组件中显示该角色的计数。

我正在为每个角色编写过滤功能。那是可行的,但是我怎样才能改进我的代码而不是重复我自己?

正如@UnholySheep 已经在评论中提到的那样:

function getUsersByRole(users, role) {
  return users.filter((u) => u.role == role));
}

然后您可以为您想要的每个角色调用它。

您甚至可以使用某种 groupBy 函数,例如来自另一个 SO post 的函数:

let groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

然后只需调用

let grouped = groupBy(users, 'role');
// returns {pro: Array(4), customer: Array(2)}

也许您可以尝试创建一个函数,该函数可以按角色过滤用户,returns 一个特定用户按角色排列的数组,我试过了,您可以看看这个。

import Card from "./Card";
import "./styles.css";

export default function App() {
  const users = [
    { id: 34, name: "A", role: "pro" },
    { id: 43, name: "B", role: "customer" },
    { id: 35, name: "C", role: "pro" },
    { id: 55, name: "D", role: "pro" },
    { id: 67, name: "test", role: "pro" },
    { id: 543, name: "Jhon", role: "customer" }
  ];

  const customer = checkUserByRole('customer');

  const pro = checkUserByRole('pro');

  function checkUserByRole(role) {
    const filteredUser  = users.filter((user) => {
      return user.role === role;
    });
    return filteredUser;
  }
  return (
    <div className="App">
      <Card role={"Customer"} count={customer.length} />
      <Card role={"Pro"} count={pro.length} />
    </div>
  );
}

}