在 JavaScript 中過濾物件陣列
Shiv Yadav
2022年7月18日
本文將教你如何使用 JavaScript filter()
函式過濾陣列中的元素。
在 JavaScript 中過濾物件陣列
使用陣列時,最典型的工作之一是構建一個包含原始陣列成員子集的新集合。假設你有多個學生物件,每個物件都有兩個屬性:sports
和 subjects
。
const students = [
{ sports: ["cricket", "football"], subjects: "Science" },
{ sports: ["Badminton", "Hockey"], subjects: "Math" },
{ sports: ["Chess", "cricket"], subjects: "Computer Science" },
{ sports: ["Judo", "football"], subjects: "Social Science" },
];
要找到最喜歡的運動是板球的學生,你必須像這樣過濾包含 cricket
的運動:
const Cricket = students.filter((e) => e.sports.includes("cricket"));
console.log(Cricket);
輸出:
[{
name: "Johnny",
sports: ["cricket", "football"]
}, {
name: "Dev",
sports: ["Chess", "cricket"]
}]
在這個例子中,我們使用了 students
陣列物件的 filter()
方法並傳遞了一個測試每個成員的程式。在函式中,我們確定陣列中每個學生的運動是否對應於 cricket
。
如果是這種情況,函式返回 true
;否則,它返回 false
。filter()
方法僅包含返回陣列中傳遞迴調函式條件的那些元素。
Author: Shiv Yadav
Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.
LinkedIn