json - How do I access an array inside a json object?
问题描述
I am using axios to access the OMDB api. The returned value is saved to a ref([]) object called ombdRatings in my vue component, and I'm trying to access these values to be displayed in the DOM. Here's the returned json:
{"Title":"Parasite","Year":"1982","Rated":"R","Released":"12 Mar 1982","Runtime":"85 min","Genre":"Horror, Sci-Fi","Director":"Charles Band","Writer":"Alan J. Adler, Michael Shoob, Frank Levering","Actors":"Robert Glaudini, Demi Moore, Luca Bercovici","Plot":"In a post-apocalyptic USA, a doctor/scientist infected with a new strain of parasite ends up in a small desert town, trying to find a cure.","Language":"English","Country":"United States","Awards":"N/A","Poster":"https://m.media-amazon.com/images/M/MV5BMTFlZDVjMDMtODkwNS00MTM3LWJiMzQtY2IxN2JiNWZjMWUxXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"4.0/10"},{"Source":"Rotten Tomatoes","Value":"17%"}],"Metascore":"N/A","imdbRating":"4.0","imdbVotes":"2,574","imdbID":"tt0084472","Type":"movie","DVD":"30 Oct 2017","BoxOffice":"N/A","Production":"Embassy Pictures","Website":"N/A","Response":"True"}
The ratings are stored in an array in my object. When I try to access the first item on the array to display in the DOM like: {{ omdbRatings.Ratings[0] }}
then I get an error like
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '1')
I can access other items in the object, but I don't know how I can access this array in my DOM with interpolation.
解决方案
when axios is not done ,ratings and Value are undefined,so it is wrong. you can need to ratings is exist。you wirte code:
<div v-if="omdbRatings&&omdbRatings.Ratings&&......">.....</div>
This is tedious.
Simple,code is right. in js,you can:</p>
console.log(omdbRatings?.Ratings?.[0]?.Value||'--');
but template,you need template supposed Optional_chaining:</p>
export const optionalChaining = (obj, ...rest) => {
let tmp = obj;
for (let key in rest) {
let name = rest[key];
tmp = tmp?.[name];
}
return tmp || "";
}
so,template use:
{{optionalChaining(omdbRatings,"Ratings",'0','Value')||'--'}}
推荐阅读
- algorithm - 如何计算一百万个二进制序列的不同组?
- beautifulsoup - 查找特定的数据可用性类
- android - 在内核中创建服务,在 Android 上监控多个包
- javascript - 将每个数组的子元素组合成一个新的最终数组 - JavaScript
- python - 过滤一组中超过1个值的行并计算它们的出现pandas python
- entity-framework-core - 内存数据库的单元/集成测试不适用于 IQueryables
- java - 附加java静态变量
- gitlab - 有没有办法根据 GitlabCI 中的不同文件更改触发合并请求上的不同提交构建?
- r - R中二进制序列的函数
- matlab - Matlab - 使用'buttondownfcn'获取按钮点击线图的日期x坐标