Home > other >  How do I access an array inside a json object?
How do I access an array inside a json object?

Time:09-29

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.

CodePudding user response:

omdbRatings is array so try:

{{ omdbRatings[0].Ratings[0] }}

CodePudding user response:

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:

console.log(omdbRatings?.Ratings?.[0]?.Value||'--');

but template,you need template supposed Optional_chaining:

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')||'--'}}
  • Related