简体   繁体   English

比较数组中的对象属性

[英]Comparing object properties in an array

Have a set of objects stored in an array. 将一组对象存储在一个数组中。 If I want to compare an attribute like weight, how would I do it in the most effective way? 如果我想比较一个像重量这样的属性,我该如何以最有效的方式做到这一点? Let's say i want the fruitbasket to be full when weight = 10. 假设当重量= 10时,我希望水果篮充满。

var fruitBasket = []
function addFruit(fruit, weight) {
 return {
  fruit: fruit,
  weight: weight  
 }
}
fruitBasket.push(addFruit(apple, 2));
fruitBasket.push(addFruit(orange, 3));
fruitBasket.push(addFruit(watermelon, 5));
//etc...

You would need to maintain a sum of the weights in the fruitBasket array somewhere, and before you add you should check it against the added weight of an item. 您需要在fruitBasket数组中的某处保持权重总和,在添加之前,应根据项目的附加权重进行检查。 No need to worry too much about the individual weight of an added item via accessing through the array -> object, instead let your function handle it. 通过访问数组 - >对象,无需过多担心添加项目的个别权重,而是让您的函数处理它。

var totalWeight = 0,
    maxWeight = 10;

function addFruit(fruit, weight) {
  // Adds items to the fruit basket iff weight does not exceed maxWeight
  if((totalWeight + weight) <= maxWeight) {
    totalWeight += weight;
    return {
      fruit: fruit,
      weight: weight  
    }
  }
}

For the specific example you gave I would use Array.reduce method as below: 对于您给出的具体示例,我将使用Array.reduce方法,如下所示:

var weight =fruitBasket.reduce(function(a,b){return a.weight + b.weight})

Which would give you the overall weight. 哪个会给你整体的重量。 Reduce info ( https://www.w3schools.com/jsref/jsref_reduce.asp ) 减少信息( https://www.w3schools.com/jsref/jsref_reduce.asp

However, the answer might depend on what you mean as effective (ie efficient, best performance, most readable etc) 但是,答案可能取决于你的意思是什么有效(即有效,最佳性能,最可读等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM