【问题标题】:Looping Through and Displaying Deeply Nested Objects/JSON with React使用 React 循环并显示深度嵌套的对象/JSON
【发布时间】:2021-05-25 07:22:56
【问题描述】:

我正在发出 API 请求并通过 groupBy 和 sortBy 运行数据,以获得稍微结构化的对象。然后我将它保存到状态。

useEffect(() => {
        const fetchTeamData = async () => {
            const result = await axios(
              `https://example.com/api-call`,
            ).then((result) => {
                let teams = _.groupBy(_.sortBy(result.data.results, "season"), "player_profile.team");
                setTeamInfo(teams);
            });
          };
          fetchTeamAffinityData(); 
      }, []);

这给了我一个类似的对象:

{
    Angels: [
        0: {
            player_profile:{
                name: "John Doe",
                number: "10"
            },
            season: 1
        },
        1: {
            player_profile:{
                name: "Mike Trout",
                number: "21"
            },
            season: 2
        }
    ],
    Diamondbacks: [
        0: {
            player_profile:{
                name: "Randy Johnson",
                number: "51"
            },
            season: 1
        },
        1: {
            player_profile:{
                name: "Brandon Webb",
                number: "16"
            },
            season: 2
        }
    ],
}

这是我正在寻找的输出:

Team: Angels
Player 1: John Doe
Player 1 Number: 10
Player 2: Mike Trout
Player 2 Number: 21

Team: Diamondbacks
Player 1: Randy Johnson
Player 1 Number: 51
Player 2: Bradon Webb
Player 2 Number: 17

这是我尝试过的,它为我提供了团队名称的循环。但是由于我正在映射对象键,因此我丢失了嵌套对象的实际数据。

{Object.keys(teamAffinityInfo?? "").map((team, index) => (
    Team: {team}
))}

如何以合理的方式处理深度嵌套的对象?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

根据您的方法,您可以存储 Object.keys() 然后迭代这些键以实现您的逻辑。

JS

const teams = Object.keys(object1)

teams.forEach(team => {
   const playerProfiles = Object1[team]

   playerProfiles.forEach(p => {
      // Your logic here
   })

})

更好的方法是使用 Ogod 在评论中提到的 Object.entries()。

JS

const object1 = {
    Angels: [
        {
            player_profile:{
                name: "John Doe",
                number: "10"
            },
            season: 1
        },
        {
            player_profile:{
                name: "Mike Trout",
                number: "21"
            },
            season: 2
        }
    ],
    Diamondbacks: [
        {
            player_profile:{
                name: "Randy Johnson",
                number: "51"
            },
            season: 1
        },
        {
            player_profile:{
                name: "Brandon Webb",
                number: "16"
            },
            season: 2
        }
    ],
}


for (const [key, value] of Object.entries(object1)) {
  const players = value
  console.log("Team", key)
  players.forEach((p,i) => {
    console.log("Player",i, ":", p.player_profile.name) 
    console.log("Player",i, "Number :", p.player_profile.number) 
  })
}

注意:我稍微改变了对象的结构,删除了profiles数组中的索引。

【讨论】:

    【解决方案2】:

    这是一个使用object-scan的迭代解决方案

    // const objectScan = require('object-scan');
    
    const myData = { Angels: [ { player_profile: { name: "John Doe", number: "10" }, season: 1 }, { player_profile: { name: "Mike Trout", number: "21" }, season: 2 } ], Diamondbacks: [ { player_profile: { name: "Randy Johnson", number: "51" }, season: 1 }, { player_profile: { name: "Brandon Webb", number: "16" }, season: 2 } ], };
    
    const extract = (data) => {
      const logic = {
        '*': ({ key }) => `Team: ${key[0]}`,
        '*[*].player_profile.name': ({ key, value }) => `Player ${key[1] + 1}: ${value}`,
        '*[*].player_profile.number': ({ key, value }) => `Player ${key[1] + 1} Number: ${value}`
      }
      return objectScan(Object.keys(logic), {
        breakFn: ({ context, matchedBy, key, value }) => {
          context.push(...matchedBy.map((m) => logic[m]({ key, value })))
        },
        reverse: false
      })(data, []);
    }
    
    console.log(extract(myData).join('\n'));
    /* =>
    Team: Angels
    Player 1: John Doe
    Player 1 Number: 10
    Player 2: Mike Trout
    Player 2 Number: 21
    
    Team: Diamondbacks
    Player 1: Randy Johnson
    Player 1 Number: 51
    Player 2: Brandon Webb
    Player 2 Number: 16
    */
    .as-console-wrapper {max-height: 100% !important; top: 0}
    <script src="https://bundle.run/object-scan@16.0.2"></script>

    免责声明:我是object-scan的作者

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 2021-05-08
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2017-06-27
      • 2019-03-15
      • 2019-07-19
      相关资源
      最近更新 更多