How to safely access nested properties in Amazon product data using JavaScript?

I'm working with Amazon product data in JavaScript and running into issues when certain properties are missing. Here's what I'm trying to do:

const price = success.data[i].OfferSummary[0].LowestNewPrice[0].Amount;

The problem is, if any of these nested objects don't exist, I get an error. I could check each level like this:

if (success.data[i] && success.data[i].OfferSummary && success.data[i].OfferSummary[0] /* and so on */) {
  // access the price
}

But that seems really clunky. Is there a better way to handle this? I thought about using try/catch, but I'm wondering if there's a more elegant solution. Has anyone dealt with this kind of nested data before? What's the best practice here?

hey, u could try using lodash’s _.get() function. it’s pretty handy for this stuff. like:

const price = _.get(success, ‘data[i].OfferSummary[0].LowestNewPrice[0].Amount’, ‘N/A’);

it’ll give u the price or ‘N/A’ if it can’t find it. no need for all those checks!

Another approach you might consider is using the Object.prototype.hasOwnProperty() method in combination with a recursive function. This allows you to safely traverse the object structure without relying on external libraries:

function safelyGetNestedProperty(obj, path) {
return path.split(‘.’).reduce((acc, part) => {
return acc && acc.hasOwnProperty(part) ? acc[part] : undefined;
}, obj);
}

const price = safelyGetNestedProperty(success, ‘data[i].OfferSummary[0].LowestNewPrice[0].Amount’);

This method is flexible and can handle various levels of nesting. It’s also pure JavaScript, so you don’t need to import any additional libraries. Just make sure to handle the case where ‘price’ might be undefined in your subsequent code.

I’ve faced similar challenges when working with deeply nested data structures, especially from APIs. One approach I’ve found quite effective is using the optional chaining operator (?.) introduced in ES2020. It allows you to safely access nested properties without throwing an error if a property is undefined or null.

For your specific case, you could rewrite it like this:

const price = success.data[i]?.OfferSummary?.[0]?.LowestNewPrice?.[0]?.Amount;

This way, if any part of the chain is undefined, it’ll just return undefined instead of throwing an error. You can then check if ‘price’ is undefined and handle it accordingly.

Another useful trick is combining this with the nullish coalescing operator (??) to provide a default value:

const price = success.data[i]?.OfferSummary?.[0]?.LowestNewPrice?.[0]?.Amount ?? ‘N/A’;

This approach has made my code much cleaner and more robust when dealing with nested data structures from various APIs.