[英]Map input array and get filtered array of object as result
我有以下來自后端的數據。
priorities: [ 'get license', 'enroll college' ];
現在,我在前端有一個硬編碼的對象列表。
studentPriorities = [
{
prioritiesTitle: "get license",
prioritiesDescription: "go to DMV and get your license"
},
{
prioritiesTitle: "enroll college",
prioritiesDescription: "gather fees and enroll for college"
},
{
prioritiesTitle: "give exams",
prioritiesDescription: "study hard for the exams"
}
]
在任何時候,我都會得到 2 個優先級作為后端響應。 我需要搜索我的硬編碼對象數組並獲取最終數據,如下所示。
mappedStudentPriorities = [
{
prioritiesTitle: "get license",
prioritiesDescription: "go to DMV and get your license"
},
{
prioritiesTitle: "enroll college",
prioritiesDescription: "gather fees and enroll for college"
}
]
有人可以建議我如何實現這一目標嗎?
這可以簡單地使用Array.filter
& Array.includes
。
使用Array.includes
可以檢查元素是否包含在數組中,使用Array.filter
可以得到滿足條件的過濾結果。
const priorities = [ 'get license', 'enroll college' ]; const studentPriorities = [ { prioritiesTitle: "get license", prioritiesDescription: "go to DMV and get your license" }, { prioritiesTitle: "enroll college", prioritiesDescription: "gather fees and enroll for college" }, { prioritiesTitle: "give exams", prioritiesDescription: "study hard for the exams" } ]; const result = studentPriorities.filter(({ prioritiesTitle }) => priorities.includes(prioritiesTitle)); console.log(result);
我更喜歡使用 indexOf 因為舊瀏覽器和一些新瀏覽器不支持包含
const result = studentPriorities.filter(({ priorityTitle }) => (priorities.indexOf(prioritiesTitle) !== -1));
控制台日志(結果);
您可以在從后端獲得的數組上使用Array.prototype.flatMap
,然后在數據條目上使用Array.prototype.filter
。 一個函數可能如下所示:
/** @param {string[]} priorities the titles you want to match */
function filterByPriorities (...priorities) {
return priorities.flatMap(priority => studentPriorities.filter(({ prioritiesTitle }) => prioritiesTitle === priority))
}
基本邏輯是:
input
每個字符串
dataset
,其中:
prioritiesTitle
匹配input
return
結果現在這里沒有太大的優勢,但如果數據變得更復雜,使用for...of
-loop 通常是一個好主意。 下面的函數將給出相同的結果,但對於復雜的操作,這往往更容易理解和維護。
dataset
每個entry
input
包括條目標題
entry
推entry
out-array
out-array
/** @param {string[]} priorities the titles you want to match */
function filter2 (...priorities) {
const out = []
for (const { prioritiesTitle, ...rest } of studentPriorities) {
if (priorities.includes(prioritiesTitle)) out.push({ prioritiesTitle, ...rest })
}
return out
}
兩者的預期輸出是:
[
{
prioritiesTitle: 'get license',
prioritiesDescription: 'go to DMV and get your license'
},
{
prioritiesTitle: 'enroll college',
prioritiesDescription: 'gather fees and enroll for college'
}
]
Array.prototype.includes
相當多的開發人員建議使用Array.prototype.indexOf
而不是Array.prototype.includes
因為.includes
並非在所有瀏覽器中都可用。 但有幾點需要注意:
Array.prototype.includes
.includes
相比,大型數據集的.indexOf
可能意味着巨大的速度損失(從如果項目位於結果末尾時稍微慢一點,到 v8 中operations/s
減少 1000 倍( Chrome、nodejs 等)當項目接近數組的開頭時。 src ).includes
因為絕大多數用戶將使用支持它的瀏覽器。*通用瀏覽器 -> 具有常用 JS 引擎之一的瀏覽器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.