简体   繁体   English

从数组中的所有javascript对象添加特定属性的值

[英]Adding values of a particular property from all javascript objects in an array

I have an array of javascript objects: 我有一个javascript对象数组:

var myObjects = [{figure: 3}, {figure: 5}, {figure: 2}];

I would like code that could give me a total of 10 based on the addition of all figure properties of objects in myObjects . 我希望基于myObjects中对象的所有figure属性的添加,总共可以得到10个代码。

What I've Tried/Done 我尝试过/完成的

I could loop through using jQuery's .each() but I don't feel like iterating (and using a temporary 'store' variable) is the most elegant. 我可以遍历使用jQuery的.each()但是我不觉得迭代(和使用临时的“ store”变量)是最优雅的。

Obviously I could also do: 显然我也可以:

myObjects[0] + myObjects[1] etc. - but assume there is an arbitrary amount of objects. myObjects[0] + myObjects[1]等-但假定存在任意数量的对象。

I've done something similar for getting the minimum already: 我已经做了一些类似的事情来获得最低要求:

var lowest = Math.min.apply(null, myObjects.map(function (x) { return x['figure']; }));

But would like the equivalent for total. 但是想要相当于总数。

You could use Array.prototype.reduce : 您可以使用Array.prototype.reduce

var data = [{figure: 3}, {figure: 5}, {figure: 2}],
    sum = data.reduce(function(memo, c) { return memo + c.figure }, 0);

reduce is part of ECMAScript 5, so it is available in IE9+ and recent versions of all other browsers - see this compatibility table . reduce是ECMAScript 5的一部分,因此它在IE9 +和所有其他浏览器的最新版本中可用-请参阅此兼容性表

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

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