1

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]

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Lalas M
  • 1,116
  • 1
  • 12
  • 29
  • 1
    Filter the array using `Array.prototype.filter`. I'm sure there are multiple similar questions. – Ramesh Reddy Dec 17 '21 at 06:51
  • 2
    Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Ramesh Reddy Dec 17 '21 at 06:52

2 Answers2

1

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))
Deepak
  • 2,660
  • 2
  • 8
  • 23
0

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)