0

I have an js object JSON

var s = [  
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Smith A.",
      "AMOUNT":"14289.66"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Jonson B.",
      "AMOUNT":"7408.05"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Lee C.",
      "AMOUNT":"10102.98"
   }
]

I want to count summ of AMOUNT property and do it by using next (I used code from source stackoverflow_count_summ):

s.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + b[prop];
    }, 0);
};

sTotal = s.sum(s, 'AMOUNT');

but I get an error message: "TypeError: s.sum is not a function"

How can I get summ of 'AMOUNT' values through the object?

dmytro Minz
  • 407
  • 1
  • 8
  • 19

3 Answers3

1

Try to use this code:

var s = [  
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Smith A.",
      "AMOUNT":"14289.66"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Jonson B.",
      "AMOUNT":"7408.05"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Lee C.",
      "AMOUNT":"10102.98"
   }
];
s.__proto__.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + +b[prop];
    }, 0);
};

sTotal = s.sum(s, 'AMOUNT');
console.log(sTotal);

I set function into proto and add type convert in return. I tested it in Firefox, Chrome, and Edge it works fine.

0

I am not here to tell you exactly how you should perform this, but I will answer your question in a format that is closely resembling what you posted here. You can simply parse the string you have in the AMOUNT property, and convert it to a floating point number.

s.sum = function(arr) {
  return arr.reduce(function(acc, obj) {
    return acc += parseFloat(obj.AMOUNT);
  }, 0);
}

You can check out a working example in this codepen.

Dan Zuzevich
  • 3,651
  • 3
  • 26
  • 39
0

First of all I got error message because my s was a string type, so I have to convert it to an array.

AND function with proto - works for me

s.__proto__.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + +b[prop];
    }, 0);
};

sTotal = s.sum(s, 'AMOUNT');
console.log(sTotal);

thank you all guys

dmytro Minz
  • 407
  • 1
  • 8
  • 19