简体   繁体   中英

Reading JSON response and getting type error for field in response even though field exists javaScript

my previously working code has stopped reading one of the inner fields in my JSON response, saying there is a type error even though the field exists.

Here's the response I'm reading:

organic_results: [{title: "Montessori Wooden Educational Object Permanence Box With Tray For Toddlers Kid",…},…]
0: {title: "Montessori Wooden Educational Object Permanence Box With Tray For Toddlers Kid",…}
condition: "Brand new"
extensions: ["Buy It Now", "Almost gone", "85 sold"]
price: {raw: "AU $23.85", extracted: 23.85}
extracted: 23.85
raw: "AU $23.85"
shipping: "Postage not specified"
subtitle: "Unbranded"
thumbnail: "https://i.ebayimg.com/thumbs/images/g/1eMAAOSw5Jdf9SA9/s-l225.jpg"
title: "Montessori Wooden Educational Object Permanence Box With Tray For Toddlers Kid"

If I hover over the fields I see the path organic_results[0].price.extracted

In my code I'm looping through the results and adding them all, then dividing to get the average sale price.

const { organic_results } = await response.json();

    //find total price by adding all prices from the found records
    const averagePrice = () => {
    let total = 0;
    let average = 0;

    for (let index = 0; index < organic_results.length; index++) {
      let priceMinusPostage = organic_results[index].price.extracted - 9; //Guestimate of average postage
      total = total+priceMinusPostage;
    }

    average = (total/organic_results.length).toFixed(2);
    return average;
    }

When I run my code I get a TypeError:

TypeError: Cannot read properties of undefined (reading 'extracted')

What's the dumb thing that I'm just not seeing atm?

Do it in this way, it should work if you have it in response

organic_results[index]?.price?.extracted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM