2

I have an array of objects coming from an api that looks like this

[{"HomeTeam": "HOU"}, {"AwayTeam": "GB"}, {"HomeTeam": "DAL"}, {"AwayTeam": "TB"}]

I'm using map to map over the objects and get the team names to put them into react table like this.

const results = data.map((teams) => ({
    "Teams": // I need both teams here
}))

How can I map over the array and get both HomeTeam and AwayTeam values into Teams values?

I need the final object to look like this

[{"Teams": "HOU"}, {"Teams": "GB"}, {"Teams": "DAL"}, {"Teams": "TB"}]
 
5
  • 2
    I'm not exactly sure what your desired outcome is, but I feel that the reduce method would help you Commented Oct 24, 2020 at 18:59
  • 1
    That's a horrible api. Use data.flatMap(Object.entries) then work with the tuples Commented Oct 24, 2020 at 19:12
  • 1
    const results = data.map(team => ({ Teams: team.HomeTeam || team.AwayTeam })); Commented Oct 24, 2020 at 19:35
  • As Bergi said, this is a very bad API, the response should be at least like: { team: Name, type: HomeTeam/AwayTeam } or return a match object like so: { HomeTeam: Name, AwayTeam: Name } Commented Oct 24, 2020 at 19:44
  • Didn't build the api so I have no control over it Commented Oct 24, 2020 at 19:46

1 Answer 1

3

If the objects only have one key, this should be fine.

const data = [{"HomeTeam": "HOU"}, {"AwayTeam": "GB"}, {"HomeTeam": "DAL"}, {"AwayTeam": "TB"}];

const results = data.map(td => ({ Teams: Object.values(td)[0] }));

console.log(results);

Sign up to request clarification or add additional context in comments.

2 Comments

...or use Object.values like so: { Teams: Object.values(td)[0] }.
Yes, that's cleaner. I'll edit with your suggestion.

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.