angular - 在Angular应用程序中,访问JSON数据

如何从给定对象访问'行'数据?这是api的链接- https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json


{


"events": [{


"id": 153502679,


"name":"Green Bay Packers @ Chicago Bears",


"homeTeamName":"CHI Bears",


"awayTeamName":"GB Packers",


"startDate":"2019-09-06T00:20:00.0000000Z",


"offers": [{


"id":"1-2160521227",


"label":"Point Spread",


"outcomes": [{


"id":"1-2568051855",


"label":"GB Packers",


"line":"+3.5000",


"oddsAmerican":"-110",


"oddsDecimal": 1.9100,


"oddsFractional":"10/11",


"participant":"GB Packers"


 },



我得到了一个错误:


<td>{{data.name }}</td>


 <td>{{data.homeTeamName }}</td>


 <td>{{data.awayTeamName}}</td>


 <td>{{data.startDate }}</td>


 <!--<td>{{data.offers[1].label }}</td>-->


 <td>{{data.offers.outcomes[2].line }}</td>



我尝试了上面的代码,访问结果对象中的行,它给了我以下错误,


ERROR TypeError: Cannot read property '2' of undefined



时间:

可能是数据为空,或者没有你要查找的属性,另一种可能性是,你没有访问数据对象中的events数组。请尝试使用以下代码:


data.events[0].offers[0].outcomes[0].line



希望它能工作!

API响应包含3个嵌套数组,所以,你必须在访问他们的值时要考虑他们。根据下面的数组中的项的数量,解决方案将有所不同,例子中,你正在访问数组'Events','offers','outcomes'的第一个项的值。

在这种情况下,你可以尝试

<td>{{data.events[0].offers[0].outcomes[0].line}} </td>

考虑到每个嵌套aray中只有一个项,你可以访问line,


let data = {


"events": [{


"id": 153502679,


"name":"Green Bay Packers @ Chicago Bears",


"homeTeamName":"CHI Bears",


"awayTeamName":"GB Packers",


"startDate":"2019-09-06T00:20:00.0000000Z",


"offers": [{


"id":"1-2160521227",


"label":"Point Spread",


"outcomes": [{


"id":"1-2568051855",


"label":"GB Packers",


"line":"+3.5000",


"oddsAmerican":"-110",


"oddsDecimal": 1.9100,


"oddsFractional":"10/11",


"participant":"GB Packers"



 }]


 }]


 }]


}



console.log(data.events[0].offers[0].outcomes[0].line);

如果每个嵌套数组中有n个对象,则可以将,


let data = {


"events": [{


"id": 153502679,


"name":"Green Bay Packers @ Chicago Bears",


"homeTeamName":"CHI Bears",


"awayTeamName":"GB Packers",


"startDate":"2019-09-06T00:20:00.0000000Z",


"offers": [{


"id":"1-2160521227",


"label":"Point Spread",


"outcomes": [{


"id":"1-2568051855",


"label":"GB Packers",


"line":"+3.5000",


"oddsAmerican":"-110",


"oddsDecimal": 1.9100,


"oddsFractional":"10/11",


"participant":"GB Packers"



 }]


 }]


 }]


}



data['events'].forEach(event => {


 event.offers.forEach(offer => {


 offer.outcomes.forEach(outcome => {


 console.log(outcome.line);


 });


 });


});

你应该试试


 <td>{{data.offers.outcomes.line }}</td>



...