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;

  }
6
  • Why would you need an array holding single object? Where does resulted and type come from? Commented Jul 20, 2020 at 14:25
  • Looks like you're trying to do more than just convert the key/value pairs to an array. You are also adding properties like "type": "LEAGUE", is that part of your question? Commented Jul 20, 2020 at 14:25
  • Sorry, I should have mentioned resulted and type are hardcoded. Commented Jul 20, 2020 at 14:26
  • 2
    Does this answer your question? How to convert an Object {} to an Array [] of key-value pairs in JavaScript Commented Jul 20, 2020 at 14:26
  • 1
    Have you try using Object.values(yourObject) ? Commented Jul 20, 2020 at 14:29

2 Answers 2

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,
    },
    
    }) ?? [];
Sign up to request clarification or add additional context in comments.

3 Comments

this may be an answer, however do you think you can use javascript reduce method ?
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.
hmmm i see, i see.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.