簡體   English   中英

如何根據 JavaScript 中的給定條件過濾對象?

[英]How to filter objects based on given condition in JavaScript?

我是這個社區的新手,剛開始編程我找不到關於這個主題的任何信息,任何人都可以解決這個問題。 我需要過濾數組中每個點都超過 75 的名稱。我已經嘗試過這個並且無法迭代數組。

 const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}] const arrayOfSelecetedCandidates=[] for(let object of candidatesList){ if (candidatesList.every(candidatesList.points>75)){ arrayOfSelecetedCandidates.push(candidatesList.name) } } console.log(arrayOfSelecetedCandidates);

也許你想要這個?

 const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}] const arrayOfSelecetedCandidates=[] for(let object of candidatesList){ if (object.points.every(i=>i>75)) arrayOfSelecetedCandidates.push(object.name) } console.log(arrayOfSelecetedCandidates);

但正如@Dai 指出的那樣,如果你想測試一個數組並返回通過測試的項目,過濾器總是更好:

 const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}] const arrayOfSelecetedCandidates=candidatesList.filter(i=>i.points.every(y=>y>75)) console.log(arrayOfSelecetedCandidates)

您可以通過使用Array.filter()方法和Array.every()來測試數組中的所有元素是否通過提供的 function 實現的測試來實現這一點。它返回一個 Boolean 值。

工作演示:

 const candidatesList = [{ 'name': 'Blake Hodges', 'points': [76, 98, 88, 84] }, { 'name': 'James Anderson', 'points': [0, 98, 12, 13] }]; let res = candidatesList.filter((obj) => { return obj.points.every((item) => item > 75) }); console.log(res);

“我需要過濾數組中每個點都在 75 以上的名字”

查看OP的內容,我認為這是不正確的。 如果所需的 output 只是平均點數等於或高於 75 的對象(又名候選對象)而不是總共 75 點(盡管解釋得不是很好),那將更有意義。 所以攻擊計划是:

  • 使用for...of循環獲取每個候選人:

     for (const candidate of candidates) {...
  • 獲取每個候選點 ( candidate.points ) 並使用.reduce()獲取它們的總和(注意:返回轉到一個名為.total的新屬性)。 然后取該總數並除以 points 數組中的成績數(它是candidate.points.length = 4):

     candidate.total = candidate.points.reduce((sum, cur) => sum + cur, 0); candidate.gpa = Math.floor(candidate.total / candidate.points.length);
  • 一旦candidate.gpa建立, .filter()將確定它是否等於或大於 75。

     return candidates.filter(candidate => candidate.gpa >= 75);

 const candidates = [{ 'name': 'Blake Hodges', 'points': [76, 98, 88, 84] }, { 'name': 'James Anderson', 'points': [0, 98, 12, 13] }, { 'name': 'Zer0 0ne', 'points': [100, 88, 91, 84] }, { 'name': 'Ronald McDonald', 'points': [72, 51, 8, 89] }]; const selected = candidates => { for (const candidate of candidates) { candidate.total = candidate.points.reduce((sum, cur) => sum + cur, 0); candidate.gpa = Math.floor(candidate.total / candidate.points.length); } return candidates.filter(candidate => candidate.gpa >= 75); }; console.log(selected(candidates));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM