Home > Software engineering >  Filter complex array in react native?
Filter complex array in react native?

Time:11-17

I have array .

const arr = [{
    "status": "success",
    "data": [{
            "name": "user1",
            "games": [{
                "id": 1,
                "gamename": "cricket"
            }, {
                "id": 2,
                "gamename": "football"
            }]
        },
        {
            "name": "user1",
            "games": [{
                "id": 1,
                "gamename": "videogames"
            }, {
                "id": 2,
                "gamename": "volleyball"
            }]
        }
    ]
}]

I tried following the code to filter it. and no output show

arr.map((item,idx) => (
  
       console.log(item.data.games.gamename)
   )
  ))

I want to print all game name eg.

cricket football videogames volleyball

CodePudding user response:

We can use flatMap() to do it

const arr = [{
    "status": "success",
    "data": [{
            "name": "user1",
            "games": [{
                "id": 1,
                "gamename": "cricket"
            }, {
                "id": 2,
                "gamename": "football"
            }]
        },
        {
            "name": "user1",
            "games": [{
                "id": 1,
                "gamename": "videogames"
            }, {
                "id": 2,
                "gamename": "volleyball"
            }]
        }
    ]
}]

// multiple flatMap chain invocation seems ugly,waiting for more elegant solution
let result = arr.flatMap(a => a.data).flatMap(a => a.games).flatMap(a => a.gamename)
console.log(result)

CodePudding user response:

Data is a array and so is games:

const arr = [
  {
    status: "success",
    data: [
      {
        name: "user1",
        games: [
          {
            id: 1,
            gamename: "cricket",
          },
          {
            id: 2,
            gamename: "football",
          },
        ],
      },
      {
        name: "user1",
        games: [
          {
            id: 1,
            gamename: "videogames",
          },
          {
            id: 2,
            gamename: "volleyball",
          },
        ],
      },
    ],
  },
];

arr.map((item) => {
  item.data.map((item) => {
    item.games.map((item) => {
      console.log(item.gamename);
    });
  });
});

  • Related