我正在尝试在以下部分JSON中访问“ 15.00”,但是如果我使用object.shipping.rates.rate.amount,则会出现“未定义不是对象”错误。我认为令我困扰的是JSON包含两个“ region_code”,当我调用该属性时,Javascript不知道该给我哪个。而且我不知道该如何告诉我与“ US_CON” region_code关联的那个。我该如何指定?谢谢。
"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"
}
答案 0 :(得分:0)
object.shipping.rates
是一个数组。您将无法像这样访问它。
请使用索引或循环。
索引
console.log(object.shipping.rates[0].rate.amount)
循环
Object.keys(object.shipping.rates).map(key => {
console.log(object.shipping.rates[key].rate.amount)
})
答案 1 :(得分:0)
您可以使用find
来获得region_code为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);