在react native中过滤复杂数组?

uklbhaso  于 2022-11-25  发布在  React
关注(0)|答案(3)|浏览(143)

我有阵。

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,idx) => (
  
       console.log(item.data.games.gamename)
   )
  ))

我想打印所有游戏名称。
电子游戏排球

xxls0lw8

xxls0lw81#

数据是数组,游戏也是数组:

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);
    });
  });
});
qvtsj1bj

qvtsj1bj2#

试试这段代码,它将只返回游戏名称,如果不需要逗号(,),您可以更改join
输出:“板球、足球、电子游戏、排球”

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"
        }]
    }
]
}];
console.log(JSON.stringify(arr.filter(e=>e.status=="success").map(e=>e.data.map(f=>f.games.map(g=>g.gamename)).join(",")).join(",")));
eyh26e7m

eyh26e7m3#

我们可以使用flatMap()来执行此操作

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)

相关问题