user1483363
user1483363

Reputation:

How to sum attributes of different objects?

JS noob here. How can I set a variable equal to the sum of the currentDays attributes of all three animal objects?

var foods = {

chicken: {
  'days': 1349.5,
  'deaths': 28.63,
  'currentDays': 1349.5,
  'currentDeaths': 28.63
  },

eggs: {
  'days': 456.25,
  'deaths': 1.733,
  'currentDays': 456.25,
  'currentDeaths': 1.733
  },

pork: {
  'days' :112.5,
  'deaths': .445,
  'currentDays': 112.5,
  'currentDeaths': .445
  },

};

Upvotes: 0

Views: 62

Answers (3)

kojiro
kojiro

Reputation: 77167

If you can count on a recent JavaScript engine, you can use the reduce method of the Array type:

Object.keys(foods).reduce(function (p,v,i,a) {
    return p + foods[v].currentDays;
}, 0);

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 220136

var key, days = 0;

for (key in food) {
  if ( Object.prototype.hasOwnProperty.call(food, key) ) {
    days += foods[key].currentDays;
  }
}

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208695

var sum = 0;
for (var k in foods) {
    if (foods.hasOwnProperty(k))
        sum += foods[k].currentDays;
}

JSFiddle: http://jsfiddle.net/dWCAu/

Upvotes: 0

Related Questions