Home > Software design >  How to get the value of a key from a nested JSON structure by using another value in the same data
How to get the value of a key from a nested JSON structure by using another value in the same data

Time:12-17

I have a nested JSON structure, how can I return a specific value of a key from the structure depending on the value of an another key from the same structure.

Eg: My initial JSON is as follows

{
  "movies": [
    {
      "movie_name": "The Unforgivable",
      "movie_details": {
        "director": "Nora Fingscheidt",
        "lead_actor": "Sandra Bullock",
        "genre": {
          "romance": "no",
          "drama": "yes",
          "action": "no",
          "comedy": "no"
        }
      }
    },
    {
      "movie_name": "The Power Of The Dog",
      "movie_details": {
        "director": "Jane Campion",
        "lead_actor": "Benedict Cumberbatch",
        "genre": {
          "romance": "yes",
          "drama": "yes",
          "action": "no",
          "comedy": "no"
        }
      }
    }
  ]
}

From this above structure I need to return the directors name who has done romance movie

so using the key value pair "romance": "yes" I need to return the director value.

In this example I'm expecting the result as [Jane Campion]

CodePudding user response:

You can use filter to filter romance movies, and then map the directors' names using map.

var data = { "movies": [ { "movie_name": "The Unforgivable", "movie_details": { "director": "Nora Fingscheidt", "lead_actor": "Sandra Bullock", "genre": { "romance": "no", "drama": "yes", "action": "no", "comedy": "no" } } }, { "movie_name": "The Power Of The Dog", "movie_details": { "director": "Jane Campion", "lead_actor": "Benedict Cumberbatch", "genre": { "romance": "yes", "drama": "yes", "action": "no", "comedy": "no" } } } ] } 

console.log(data.movies.filter(movie => movie.movie_details.genre.romance == "yes").map(directorsArr => directorsArr.movie_details.director))

CodePudding user response:

At the first, you need to filter your objects based on romance genre.

let romanceMovies = data.movies.filter(movie => movie.movie_details.genre.romance === "yes")

then when you have romance movies you can map the result to get the directors name.

let romanceDirectors = romanceMovies.map(movie => movie.movie_details.director)
  • Related