-4

take an object, containing several objects. Those objects can have a specific key called number, whose value is a number. How can I addition all the "number" value of the objects that have this key number...

var myObject = {
    item1 = {
        name: "someName",
        color: "someColor2", 
        number: intValue
     },
     item2 = {
        name: "someName2",
        color: "someColor2"
     },
     item3 = {
        name: "someName3",
        color: "someColor3", 
        number: intValue
     },
     item4 = {
        name: "someName4",
        color: "someColor4" 
     },
};
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
user1859295
  • 63
  • 1
  • 10
  • 2
    Have you tried anything? – Pritam Banerjee Jan 25 '17 at 22:00
  • Iterate through the objects and access their `number` property and sum them. – Andrew Li Jan 25 '17 at 22:00
  • Just loop over each object, check if it has a `number` property, and if so, add it to a sum. Google is your friend – qxz Jan 25 '17 at 22:01
  • Please try and google the question first. I googled "iterate through javascript object containing other objects" and got [this](http://stackoverflow.com/questions/921789/how-to-loop-through-plain-javascript-object-with-objects-as-members) as the first result – Gab Jan 25 '17 at 22:09
  • The code that you're showing is not valid JavaScript. Please [edit] your answer to provide the code you're actually working with. – Heretic Monkey Jan 25 '17 at 22:14
  • Your object should probably be an array, not an object. Any time you have variables or properties with numeric suffixes, you should usually use an array instead. – Barmar Jan 25 '17 at 22:45

2 Answers2

1

This is a perfect use-case for Array.reduce! However, since your input is an object instead of an array, we'll need to use Object.keys to obtain the list of item names, which list will then drive the reducer loop.

// your object def wasn't valid, so I made my own
var myObject = {
    item1: { name: 'item one',   color: 'red',    number: 1 },
    item2: { name: 'item two',   color: 'orange', number: 2 },
    item3: { name: 'item three', color: 'yellow', number: 3 },
    item4: { name: 'item four',  color: 'green',  number: 4 },
    item5: { name: 'item five',  color: 'blue',   number: 5 },
    item6: { name: 'item six',   color: 'indigo', number: 6 },
    item7: { name: 'item seven', color: 'violet', number: 7 }
};

var total = Object.keys(myObject) //=> ['item1', 'item2', 'item3', 'item4', ...]
.reduce(function(sum, itemName) {
    return sum += myObject[itemName].number;
}, 0);
Tom
  • 8,509
  • 7
  • 49
  • 78
0
var sum = 0;

for (var prop in myObject)
{
   sum += myObject[prop].number || 0;
}

that may be a beginning of something....

ymz
  • 6,602
  • 1
  • 20
  • 39
  • Hello and thank you for the answer. I tried what you proposed but could not succeed. I also tried to do if (item.hasOwnProperty('number')) but sum stays to 0. – user1859295 Jan 27 '17 at 05:42