JavaScript将对象映射到数组

时间:2020-07-20 14:22:01

标签: javascript arrays json reactjs dictionary

我想用JavaScript转换对象,但是我不确定如何做到这一点。我不经常使用该语言编写代码,因此我并不真正了解很多基础知识-这是我从React项目中的API调用中获得的对象:

{
    "api": {
        "results": 380,
        "fixtures": [
            {
                "fixture_id": 65,
                "league_id": 2,
                "league": {
                    "name": "Premier League",
                    "country": "England",
                    "logo": "https://media.api-sports.io/football/leagues/2.png",
                    "flag": "https://media.api-sports.io/flags/gb.svg"
                },
                "event_date": "2018-08-10T19:00:00+00:00",
                "event_timestamp": 1533927600,
                "firstHalfStart": 1533927600,
                "secondHalfStart": 1533931200,
                "round": "Regular Season - 1",
                "status": "Match Finished",
                "statusShort": "FT",
                "elapsed": 90,
                "venue": "Old Trafford (Manchester)",
                "referee": null,
                "homeTeam": {
                    "team_id": 33,
                    "team_name": "Manchester United",
                    "logo": "https://media.api-sports.io/football/teams/33.png"
                },
                "awayTeam": {
                    "team_id": 46,
                    "team_name": "Leicester",
                    "logo": "https://media.api-sports.io/football/teams/46.png"
                },
                "goalsHomeTeam": 2,
                "goalsAwayTeam": 1,
                "score": {
                    "halftime": "1-0",
                    "fulltime": "2-1",
                    "extratime": null,
                    "penalty": null
                }
            }
        ]
    }
}

我想将其转换为该数组(该数组包含多个对象):

[
    {
        "homeTeam": {
            "id": 33,
            "name": "Manchester United",
            "teamId": 33
        },
        "awayTeam": {
            "id": 46,
            "name": "Leicester",
            "teamId": 46
        },
        "outcome": {
            "goalsScoredByAwayTeam": 2,
            "goalsScoredByHomeTeam": 1
        },
        "resulted": true,
        "type": "LEAGUE"
    }
]

teamIdid实际上需要在最终输出之前查找另一个对象。

我不确定最好的方法是什么。到目前为止,这是我的功能,尝试利用可选的链接:

  function convertFixturesToArray() {

    fixturesStore.getFixtures()?.api?.fixtures?.length ? fixtures.api.fixtures.map(fixture => (
      
       //TRANSFORMATION GOES IN HERE
    
     )) : null;

  }

2 个答案:

答案 0 :(得分:2)

您似乎走对了。应该是这样的(用更现代的JS编写)

  convertFixturesToArray = () => fixturesStore.getFixtures()?.api?.fixtures?.map?.(fixture => {
      
    //Do whatever check you need here with the fixture object
    return {
        homeTeam: { ...fixture.homeTeam },
        awayTeam: { ...fixture.awayTeam },
        outcome: { 
            goalsScoredByAwayTeam: fixture.goalsAwayTeam,
            goalsScoredByHomeTeam: fixture.goalsHomeTeam,
        },
        type: 'LEAGUE',
        resulted: true,
    },
    
    }) ?? [];

答案 1 :(得分:1)

您似乎正在尝试从api响应中获取某些键/值对。混合使用mapreducefind,可以通过在数组中定义它们(即desiredProps)来获得所需的值。

当然,添加"outcome"字段和其他硬编码字段将需要更多的逻辑。鲍里斯的回答解决了这个问题。我采取了一种更灵活的方法。

let apiResult = {
  "fixtures": [
    {
      "prop1": "a1",
      "prop2": "a2",
      "prop3": "a3"
    },
    {
      "prop1": "b1",
      "prop2": "b2",
      "prop3": "b3"
    }
  ]
}

let desiredProps = ["prop2", "prop3"]

let result = apiResult.fixtures.map(x => {
  return Object.keys(x).reduce((acc, curr) => {
    if (desiredProps.find(y => y === curr)) {
      acc[curr] = x[curr]
    }
    return acc
  }, {})
})

console.log(result)