David Dume David Dume - 1 year ago 56
Javascript Question

javscript- How to check if an object as a specific property

I have written this code, that i use to get 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?

Answer Source

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);