methuselah
methuselah

Reputation: 13206

Error: undefined is not an object when checking to see if property of object exists

Whenever I evaluate my object to see if a property exists, I keep getting the following error message: Error: undefined is not an object (evaluating 'a.result.hasOwnProperty').

How can I fix it?

    if(++responseCount === products.length) {
      products.sort(function(a, b) {
        if((a.result.hasOwnProperty('rawMisMatchPercentage')) && (b.result.hasOwnProperty('rawMisMatchPercentage'))) {
            return a.result.rawMisMatchPercentage - b.result.rawMisMatchPercentage;
        }
      });
      return products.slice(0, 3);
    }

Upvotes: 0

Views: 53

Answers (1)

Nemani
Nemani

Reputation: 784

Your condition should be

(a && a.result && a.result.hasOwnProperty('rawMisMatchPercentage') && (b && 
b.result && b.result.hasOwnProperty('rawMisMatchPercentage'))

Upvotes: 1

Related Questions