在获取 React 代码中唯一值之前,获取某个项目在数组中出现的次数不起作用
2021-11-04
39
在我的项目中,我有一个对象数组,我要从中获取唯一值,以便可以使用唯一值作为复选框标签。现在,这可以正常工作,但现在的问题是我需要获取值前面的出现次数。我目前无法获得它,因为值现在仅使用 Set 方法返回唯一值。表格示例.. 我想要类似 2021-10-25(3) 2021-10-18(1) 2021-10-04(2) 的内容。
链接到 replit replitlink
这是我的 App.js 代码
import "./styles.css";
import React, { useEffect, useState, useRef } from "react";
export default function App() {
const Defaultdata = [
{
date_listed: "4 hours ago",
id: "7857699961",
delivery_time_frame: "2021-10-25 - 2021-11-14",
distance: "22.8 km",
time_stamp: "2021-10-25 16:36:54",
watched: "yes"
},
{
date_listed: "3 days ago",
id: "8358962006",
delivery_time_frame: "2021-10-18 - 2021-10-24",
distance: "4.3 km",
time_stamp: "2021-10-22 16:54:12"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-25",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-04 - 2021-11-14",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-25 - 2021-10-31",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-04 - 2021-11-14",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
}
];
return (
<div className="App">
{[
...new Set(Defaultdata.map((a) => a.delivery_time_frame.substr(0, 10)))
].map((dates, i) => (
<label style={{ listStyle: "none" }} key={i}>
<input
type="checkbox"
value={dates}
/>
<span>{dates}({dates.length})</span>
</label>
))}
</div>
);
}
1个回答
您可以首先创建一个钩子
useFilteredValuesAndCounts
,它将返回一个包含
dataSet
和
countObj
的对象。
1)
dataSet
将包含唯一日期
2)
countObj
是一个包含每个日期
occurrence
的对象
现场演示
function useFilteredValuesAndCounts(arr) {
const countObj = {};
const set = new Set();
arr.forEach((a) => {
const date = a.delivery_time_frame.substr(0, 10);
countObj[date] = (countObj[date] ?? 0) + 1;
set.add(date);
});
return { dataSet: [...set], countObj };
}
export default useFilteredValuesAndCounts;
并且在您可以简单地使用 JSX:
const { dataSet, countObj } = useFilteredValuesAndCounts(Defaultdata);
return (
<div className="App">
{dataSet.map((dates, i) => (
<label style={{ listStyle: "none" }} key={i}>
<input type="checkbox" value={dates} />
<span>
{dates}({countObj[dates]})
</span>
</label>
))}
</div>
);
DecPK
2021-11-04