简体   繁体   English

从对象数组中的对象属性返回最大数字

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

I want to extract data from an Object inside an Array of Objects. 我想从对象数组中的对象中提取数据。 This is how it looks now: 现在是这样的:

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: "-"

Question: 题:
How can I get the highest score value (2) and save it to a variable? 如何获得最高分值 (2)并将其保存到变量中? Please not that there are also "-". 请不要也有“-”。

That example is no such thing as an array of objects in JavaScript. 该示例不像JavaScript中的对象数组那样。 What you are showing is an object which uses numbers as keys. 您正在显示的是一个使用数字作为键的对象。 If what you want is to retrieve the highest score value from the object you show, you can iterate through enumerable properties of an object with a for..in construct. 如果要从显示的对象中检索最高score ,则可以使用for..in构造遍历对象的可枚举属性。

So you'll have to iterate through the object, comparing the current score you're checking with the maximum value stored: 因此,您必须遍历对象,将要检查的当前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;
    }
}

You can work over the array doing something like this: 您可以对数组执行以下操作:

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

You can loop through the array, and store the score if it is bigger than the values you've encountered before: 您可以遍历数组,如果分数大于之前遇到的值,则可以存储分数:

 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 + '.'); 

You may use Reduce : 您可以使用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