0

I have this code, used to get a number of hours from an object and multiply them by a variable.

Here is the object 'work'

var work = [
    {'day': 27, 'hours': 7.30},
    {'day': 29, 'hours': 7.30},
    {'day': 31, 'hours': 10},
    {'day': 1, 'hours': 8.30},
    {'day': 2, 'hours': 7},
    {'day': 3, 'hours': 7},
    {'day': 5, 'hours': 7.30},
    {'day': 6, 'hours': 7},
    {'day': 7, 'hours': 7.30},
    {'day': 8, 'hours': 8},
    {'day': 9, 'hours': 9.30}
]

var payPerHour = 7;

and here my function to calculate the pay

function calculatePay()
{
    var result = 0, fResult = 0;

    for(var i = 0; i < work.length; i++) {
        Object.keys(work).forEach(function (val) {
            if (work[i].hasOwnProperty('hours'))
              result = work[i][val] * payPerHour;

            fResult += result;
        });
    }

    return fResult;
} 

I have used "hasOwnProperty" to check if the property "hours" exists in work. The result of the function is NaN. Why?

5
  • 2
    Object.keys(work) : what do you expect here ? Commented Sep 9, 2016 at 16:08
  • with he for loop i iterate over the array and then with Object.keys(work) i go over the object that is in the array. Commented Sep 9, 2016 at 16:12
  • @DavidDume -- You dont need to iterate the object tho. Commented Sep 9, 2016 at 16:14
  • yeah, i thought it would make sense doing so. thanks for the help Commented Sep 9, 2016 at 16:18
  • All those .30's make me wonder if your data is off a bit. Should those be .5 for half-hours? or :30 for 30 minutes, with some further translation still to do before calculation? Commented Sep 9, 2016 at 17:08

4 Answers 4

4

You're already iterating your array via the for loop - then you do

Object.keys(work).forEach(function(val) {

This doesn't make any sense. work is an array - not an object. Basically if you remove that line it'll work:

for(var i = 0; i < work.length; i++) {
  //Object.keys(work).forEach(function(val) {
    if(work[i].hasOwnProperty('hours'))
      result = work[i]["hours"] * payPerHour; //use the right property here

    fResult += result;
  //});
}

A simpler way may be to use Array.reduce

var totalHourPay = work.reduce(function(total, workDay) {
    if (workDay.hasOwnProperty("hours")) {
         total += workDay.hours * payPerHour;
    }

    return total;
}, 0);
Sign up to request clarification or add additional context in comments.

3 Comments

Or simply work.reduce((total, workDay) => total + (workDay.hours || 0) * payPerHour, 0).
@ScottSauyet -- Ya - if the ES6 syntax is available :D
Sure, the ES6 is a nice change, but also removing the hasOwnProperty check in favor of || 0 makes it more succinct, and to my eyes more readable.
0

You can use Javascript for..in loops like below:

function calculatePay() {
    var result = 0, fResult = 0;
    for(var index in work) {
      		if(work[index].hasOwnProperty('hours'))
			result = work[index]['hours'] * payPerHour;
			fResult += result;
    }
     return fResult;
 }

Comments

0

I believe this is what you wanted:

var work = [{'day': 27, 'hours': 7.30},
      {'day': 29, 'hours': 7.30},
      {'day': 31, 'hours': 10},
      {'day': 1, 'hours': 8.30},
      {'day': 2, 'hours': 7},
      {'day': 3, 'hours': 7},
      {'day': 5, 'hours': 7.30},
      {'day': 6, 'hours': 7},
      {'day': 7, 'hours': 7.30},
      {'day': 8, 'hours': 8},
      {'day': 9, 'hours': 9.30}
      ];

var payPerHour = 7;

var result = 0, fResult = 0;

function calculatePay(){

for(var i = 0; i < work.length; i++) {
   Object.keys(work).forEach(function() {

   result = work[i].hours * payPerHour;
   fResult += result;
 });

}

console.log("Final total: " +fResult);
}

calculatePay();

Comments

0

Why these complicated expressions? Try this ES6 solution:

var work = [{'day':27,'hours':7.30},{'day':29,'hours':7.30},{'day':31,'hours':10},
           {'day':1,'hours':8.30},{'day':2,'hours':7},{'day':3,'hours':7},
           {'day':5,'hours':7.30},{'day':6,'hours':7},{'day':7,'hours':7.30},
           {'day':8,'hours':8},{'day': 9, 'hours': 9.30}],
           calculatePay=(b)=>work.reduce((c,d)=>c+d.hours*b,0)

// Test
console.log( calculatePay(7) ) // Returns 600.6 and 7 is your rate per hour

// Or redefine function calculatePay this way if you need ES5 compatibility
// function calculatePay(a) {
//   return work.reduce(function(b,c) {
//     return b + c.hours * a
//   }, 0)
// }

// And if you really needs use hasOwnProperty, define it this way
// function calculatePay(a) {
//   return work.reduce(function(b,c) {
//     return b + (c.hasOwnProperty('hours') && c.hours || 0) * a
//   }, 0)
// }

// But you dont need hasOwnProperty. You are processing simple array,
// not object. And this array is full of ordinary object literals. None of
// them does not inherits anything from another object, unless you override
// Object itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.