0

I would like to convert objects in JavaScript, but I'm not really sure of the best way to do it. I don't often code in the language so I don't really know much of the fundamentals- this is the object I get back from an API call in a React project:

{
    "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
                }
            }
        ]
    }
}

I would like to convert it to this array (the array holds multiple objects):

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

The teamId and id actually need to lookup another object before the final output.

I'm not sure what the best way to do it is. This is my function so far, trying to make use of optional chaining:

  function convertFixturesToArray() {

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

  }
clattenburg cake
  • 1,096
  • 3
  • 19
  • 40

2 Answers2

2

You seem on the right track. It should be something like this (written in a slightly more modern 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,
    },
    
    }) ?? [];
  • this may be an answer, however do you think you can use javascript `reduce` method ? – BARNOWL Jul 20 '20 at 14:37
  • I don't think that this is the case to use the reduce function. The reduce function tries to reduce an array to a single value, while here we are trying to transform the values in an array to another array: each element in the fixture array will be mapped to an element in the result array. – Boris Bezzola Jul 20 '20 at 14:39
  • hmmm i see, i see. – BARNOWL Jul 20 '20 at 14:39
1

It looks like you're trying to get certain key/value pairs from your api response. With a mix of map, reduce, and find, you can get the values you're looking for by defining them in an array (i.e. desiredProps).

Of course, adding the "outcome" field and your other hardcoded fields would require a bit more logic on top of this. Boris' answer addresses this problem. I've taken a more flexible approach.

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)
Neil
  • 2,004
  • 3
  • 23
  • 48