[SOLVED] Extracting strings from complex array-object structures

Say I have the following complex structure:

  "data": {
    "queryDirector": [
      {
        "name": "Christopher Nolan",
        "films": [
          {
            "name": "The Dark Knight Rises",
            "genre": [
              {
                "name": "Thriller"
              }
            ]
          },
          {
            "name": "Batman Begins",
            "genre": []
          }
        ]
     }
  }

I need to extract only the film names and keep them in an array, i.e. an array of strings like:

var filmNames = ["Batman Begins", "The Dark Knight"]; and so on.

I’ve done this sort of thing before but I can’t seem to figure it out now; could really use the help here…

Thanks.

What have you tried so far? What problems have you run into?

I tried traversing with map like this:

var arr = [];
arr.push(obj.data.queryDirector.map(item => item.films.map(item => item.name)));

which’s giving me

[ [ [ 'The Dark Knight Rises', 'The Dark Knight' ] ] ]

I know I can extract it from there but is there any simpler way?

.map() returns an array, which is why you have a multi-dimensional array. Why are you doing a map within a map?

What is the end goal?

1 Like

as @ArielLeslie mentioned you are using two maps nested in each other and that gives you an array within an array. Then you push to the arr array and you technically have a three-dimensional array.

Is what you posted the final data you are trying to do map on or it’s just an example.
The reason I’m asking is you may not need the initial map on queryDirector since you only want the names.

the only thing map does is saying that for all the items within this array do this transaformation. So you only need to do it once and that would be when you get into the films array not queryDirector.

In either way, if you let us more info about your goal and data we might be able to give more help.

Good Luck! :call_me_hand:

1 Like

Thanks; I managed to solve it the other day…