-2

I'm trying to access "15.00" in the following partial JSON, but "undefined is not an object" error if I use object.shipping.rates.rate.amount. I think what's tripping me up is the JSON contains two "region_code"s and when I call for that property Javascript doesn't know which one to give me. And I don't know how to tell it I want the one associated with "US_CON" region_code. How can I specify? Thanks.

"shipping": {
        "free_expedited_shipping": false,
        "local": false,
        "rates": [
          {
            "region_code": "US_CON",
            "rate": {
              "amount": "15.00",
              "amount_cents": 1500,
              "currency": "USD",
              "symbol": "$",
              "display": "$15"
            }
          },
          {
            "region_code": "XX",
            "rate": {
              "amount": "50.00",
              "amount_cents": 5000,
              "currency": "USD",
              "symbol": "$",
              "display": "$50"
            }

2 Answers2

0

object.shipping.rates is an array. You would not be able to access it like that.

Please use indexing or looping.

Indexing

console.log(object.shipping.rates[0].rate.amount)

Looping

Object.keys(object.shipping.rates).map(key => {
   console.log(object.shipping.rates[key].rate.amount)
})
eenagy
  • 912
  • 1
  • 8
  • 22
0

You can use find to get the region of which the region_code is US_CON.

var shipping = {
  "free_expedited_shipping": false,
  "local": false,
  "rates": [
    {
      "region_code": "US_CON",
      "rate": {
        "amount": "15.00",
        "amount_cents": 1500,
        "currency": "USD",
        "symbol": "$",
        "display": "$15"
      }
    },
    {
      "region_code": "XX",
      "rate": {
        "amount": "50.00",
        "amount_cents": 5000,
        "currency": "USD",
        "symbol": "$",
        "display": "$50"
      }
    }
  ]
};

const region = shipping.rates.find(r => r.region_code == 'US_CON');
console.log(region.rate.amount);
Samuel
  • 422
  • 3
  • 11