我有一個物件陣列,其結構類似于:
export interface obj {
id: number,
date: string,
source: string,
}
const obj: obj[] | undefined = [
{ id: 1, date: "2021-01-17", source: "data" },
{ id: 2, date: "2021-11-23", source: "data" },
{ id: 3, date: "2020-05-03", source: "draft" },
{ id: 4, date: "2022-09-08", source: "draft" },
{ id: 5, date: "2021-12-04", source: "data" },
{ id: 6, date: "2021-09-08", source: "empty" },
];
const [objectData, setObjectData] = useState<obj[]>();
我正在嘗試回傳并呈現每種源型別的第一次出現,按最近的日期排序。因此,在上面的示例中,我想回傳 id: 5 表示“資料”、id: 4 表示“草稿”和 id: 6 表示“空”的物件。
這是我到目前為止得到的:
在useEffect中按日期降序對物件進行排序并將變數存盤在useState中
const sortByDate = obj?.slice().sort((a, b) => {
return b.date.valueOf() - a.date.valueOf();
})
然后嘗試像這樣繪制我的組件:
{objectData?.map((m) =>
m.source === "draft" ? (
<Data id={m.id} date={m.date} source={m.source} />
) : m.applicationType === "data" ? (
<Data id={m.id} date={m.date} source={m.source} />
) : m.applicationType === "empty" ? (
<Data id={m.id} date={m.date} source={m.source} />
)
)}
但這當然會渲染出每個物件。我怎樣才能只渲染出我想要的每個物件源型別的一個實體?
uj5u.com熱心網友回復:
鑒于您的方法,我會 a) 以降序方式對串列中的專案進行排序。b) 創建一個可能的唯一源名稱串列 c) 呈現唯一的源名稱并在我的降序陣列中獲取與源名稱匹配的第一項。
如果您想靜態定義源名稱串列,您可以擺脫 b)。如果是這種情況,您需要處理是否沒有找到源名稱為 selectecd 的專案。
const items = [
{ id: 1, date: "2021-01-17", source: "data" },
{ id: 2, date: "2021-11-23", source: "data" },
{ id: 3, date: "2020-05-03", source: "draft" },
{ id: 4, date: "2022-09-08", source: "draft" },
{ id: 5, date: "2021-12-04", source: "data" },
{ id: 6, date: "2021-09-08", source: "empty" },
];
// a) Sort the array with date object (descending)
const sortedArray = items.sort((a, b) => {
return new Date(b.date).valueOf() - new Date(a.date).valueOf();
});
// b) This will let you get all possible sources dynamically and create an array of unique entries
const uniqueSources = [...new Set(sortedArray.map(item => item.source))];
// c) Map over (existing) unqiue entries in the sorted list and get the first one found
uniqueSources.map((source) => {
const firstObject = sortedArray.find((entry) => entry.source === source);
console.log('source:', source, firstObject);
});
uj5u.com熱心網友回復:
我認為您可能確實(或應該)知道 的可能值source,實際上那些應該是 的型別source,例如:
export interface obj {
id: number,
date: string,
source: 'data' | 'draft' | 'empty',
}
然后在您useEffect的內部變數sortedByMostRecent中,它是按日期值排序的資料陣列。
有了它,您可以使用選項的常量陣列(在檔案頂部定義,在介面定義周圍的組件定義之外)source:
const availableSources: interface['source'][] = ['data', 'draft', 'empty'];
在排序陣列中找到與每個可用(可能)源匹配的第一個物件。就像是:
const topSourceItems = [];
for (source of availableSources) {
const topSource = sortedByMostRecent.find(item => item.source == source);
if (topSource) {
topSourceItems.push(topSource);
}
}
topSourceItems然后將存盤在狀態中并在標記中定期迭代呈現。
筆記:
你.slice()什么都沒做。也呼叫array“obj”可能不是最好的決定,但我知道這可能只是示例的虛擬代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432098.html
上一篇:使用地圖按特定順序插入物件
