Home > Blockchain >  How to loop through and display API data containing a JavaScript Object
How to loop through and display API data containing a JavaScript Object

Time:09-23

Live CodeSandbox link.

I'm trying to access and pull in data from an API, specifically the price text value below:

"price": {
  "currency": "CAD",
  "text": "500"
},

JS code (everything else pulls in fine, just the <p>${product.price.text}</p> I'm having trouble with):

// Fetch Data
async function getData() {
  const res = await fetch(url);
  const data = await res.json();
  let output = "";
  // Loop through first 'groups' array
  data.groups.map(function (group) {
    // Loop through each 'equipments' array
    group.equipments.map((product) => {
      // Define below variable to match cat products only
      const catProducts =
        product["dealer-name"] === "CATERPILLAR FINANCIAL SERVICES CORPORATION";
      // If the dealer name is everything but cat products (aka only battlefield products)..
      if (!catProducts) {
        // Loop through each 'photos' array
        product.photos.map(() => {
          // Then output the data
          // If year is undefined, replace with empty string
          output  = `
            <div class="card">
            <img class="img-fluid" src=${product.photos[0].text} alt=${
            product.model
          } />
            <div class="card--body">
              <h3>${product.year ?? ""} ${product.manufacturer} ${
            product.model ?? ""
          }</h3>
              <p>${product.city ?? "City Not Available"}, ${product.state}</p>
              <p>${product.hours} hours</p>
              <p>${product.price.text}</p> <--- Not working
              <a href='https://used.ca/en/${product["group-code"]}/${
            product["serial-number"]
          }' class="btn btn-primary">View Details</a>
              </div>
            </div>         
        `;
        });
      }
    });
  });
  // Add to slider
  $(".used-slider").slick("slickAdd", output);
}

getData();

Currently throwing a console error: "app.js:26 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'text')"

API structure:

{
  "version": "5",
  "company-code": "N001",
  "language-code": "en-CA",
  "total-count": 148,
  "created-date": "2021-09-22T18:12:03.2387128 00:00",
  "template-identifier": "4da31196-7f4b-4529-b832-90d40ef4a024",
  "group-type-code": "ProductFamilyCategory",
  "groups": [
    {
      "group-code": "Backhoe Loaders - Chargeuses-pelleteuses",
      "group-name": "Backhoe Loaders",
      "group-display-name": "Backhoe Loaders",
      "count": 7,
      "equipments": [
        {
          "id": "4536522",
          "dealer-name": "DEALER NAME",
          "GroupName": "Compact Track Loader",
          "product-family-code": "CTL",
          "product-family": "COMPACT TRACK LOADER",
          "product-family-display-name": "Compact Track Loader",
          "manufacturer-code": "CAT",
          "manufacturer": "MANUFACTURER",
          "model": "RUBBER TRACKS FOR CTL 259D ",
          "serial-number": "XXXXX",
          "year": "2016",
          "hours": 0,
          "city": "Ville St-laurent, Montréal",
          "state": "QC",
          "certification": "None",
          "availability": "Available",
          "price": {
            "currency": "CAD",
            "text": "500"
          },
          "product-family-categories": {},
          "photos": [
            {
              "text": "https://s7d2.scene7.com/is/image/CatUsedProduction/wtk?JHNyYz04ZjRjN2UyYzJkMzFmZWNjY2NiZDQ1MTc2NTA4MGY3MiYkdHh0PUJBVFRMRUZJRUxEJTIwRVFVSVBNRU5UJTIwUkVOVEFMUyUyMCUyOFFVJUMzJTg5QkVDJTI5JjUxMTY2"
            }
          ]
        }
      ]
    }
  ]
}

Anyone know why I'm unable to access the price text value but can access all the others?

CodePudding user response:

The error implies that some products don't have a price property. You need to check for this before trying to access the text property. You can display a default placeholder instead.

You can use optional chaining to simplify this.

<p>${product.price?.text || "unknown"}</p> <--- Not working
  • Related