1

I am creating a personal script that in some instances gets the error:

Cannot read property '0' of undefined

I have something like this

item["OfferSummary"][0]["LowestUsedPrice"][0]["FormattedPrice"]

Is it possible to completely ignore/override this error so that it just prints n/a or -- in that scenario?

David Mckee
  • 1,100
  • 3
  • 19
  • 35

4 Answers4

2

You can use try and catch to perform error handling.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
anurupr
  • 2,294
  • 2
  • 20
  • 28
2

You can use a boilerplate function to do so:

function get(obj, property) {      
  if (Array.isArray(property)) {
    var current = obj;
    for (var i = 0, l = property.length; i < l; ++i) {
      if (Object(current) === current) current = current[property[i]];
      else {
        current = undefined;
        break;
      }
    }
    return current;
  }
  if (Object(obj) === obj) return obj[property];
}

Pass either a string or an array to get to find the property -- if not found, undefined will be returned.

Example:

get(window, ['location', 'href']); // "http://stackoverflow.com..."
get(Number, 'MAX_VALUE'); // 1.7976931348623157e+308
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
0

Even if you can use try and catch I wouldn't do that, I prefer avoid errors at all, so you'd just need to check the object you're reading:

if(item && item["OfferSummary"].length && item["OfferSummary"][0]["LowestUsedPrice"].length) {
   //then do whatever
}

if you know that item is always defined you can avoid to check it in the if.

Darko Romanov
  • 2,776
  • 2
  • 31
  • 38
0

Similar to Qantas' answer, but using an in test. Always expects the property list to be an array, I can't see the point of using this to get a single property so no concession for that case:

function get2(obj, prop) {

    for (var i=0, iLen=prop.length - 1; i<iLen; i++) {

        if (typeof obj[prop[i]] == 'object') {
            obj = obj[prop[i]];

        } else {
            // Property not found, return undefined (or other suitable value)
            return;
        }
    }
    return obj[prop[i]];
}

var foo = {foo:{bar:{meh:'meh!'}}};
var fum = {meh:'meh!'};
console.log(get2(foo,['foo','bar','meh'])); // meh!
console.log(get2(fum,['meh']));             // meh!
console.log(get2(Number,['MAX_VALUE']));    // 1.7976931348623157e+308
console.log(get2(Object,['prototype','toString'])); // function toString() { ... }

Edit

Per Qantas' comment, the test has been updated.

RobG
  • 142,382
  • 31
  • 172
  • 209