簡體   English   中英

從對象數組中的對象屬性返回最大數字

[英]Return highest number from object property inside an Array of Objects

我想從對象數組中的對象中提取數據。 現在是這樣的:

Object
 0: Object
     id: "e0"
     score: 0
 1: Object
     id: "e1"
     score: 1
 2: Object
     id: "e2"
     score: 2
 3: Object
     id: "e3"
     score: "-"
 4: Object
     id: "e4"
     score: "-"

題:
如何獲得最高分值 (2)並將其保存到變量中? 請不要也有“-”。

該示例不像JavaScript中的對象數組那樣。 您正在顯示的是一個使用數字作為鍵的對象。 如果要從顯示的對象中檢索最高score ,則可以使用for..in構造遍歷對象的可枚舉屬性。

因此,您必須遍歷對象,將要檢查的當前score與存儲的最大值進行比較:

var max = 0;
for (var key in obj) {
    if (obj[key].score && typeof obj[key].score === 'number' && obj[key].score > max) {
        max = obj[key].score;
    }
}

您可以對數組執行以下操作:

var scores = [
  { id: 'e0', score: '2' },
  { id: 'e1', score: '0' },
  { id: 'e2', score: '-' },
  { id: 'e3', score: '1' }
];

scores
  .map(obj => parseInt(obj.score))                 // Transform each score to Integers
  .filter(val => !isNaN(val))                      // Filter the "Non Integer" values
  .reduce((acc, val) => Math.max(acc, val), -1);   // Find the highest value

您可以遍歷數組,如果分數大於之前遇到的值,則可以存儲分數:

 var items = [{id: "e0", score: 0 }, {id: "e1", score: 1 }, {id: "e2", score: 2}, {id: "e3", score: "-"}, {id: "e4", score: "-"}]; var max_score = 0; for(var i=0; i<items.length; i++) { // isNaN will tell you if the value is Not a Number if(!isNaN(items[i].score) && items[i].score > max_score) { max_score = items[i].score; } } alert('The highest score is ' + max_score + '.'); 

您可以使用Reduce

 var items = [{id: "e0", score: '-' }, {id: "e1", score: 1 }, {id: "e2", score: 2}, {id: "e3", score: "-"}, {id: "e4", score: "-"}]; var max_score = items.reduce(function(previousValue, currentValue, currentIndex, arr) { if (isNaN(previousValue.score)) { return currentValue; } if (isNaN(currentValue.score)) { return previousValue; } return (currentValue.score > previousValue.score) ? currentValue : previousValue; }).score; document.write('Reuslt = ' + max_score); 

暫無
暫無

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

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