javascript - JavaScript 将对象映射到数组
问题描述
我想在 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"
}
]
并且实际上需要在teamId
最终id
输出之前查找另一个对象。
我不确定最好的方法是什么。到目前为止,这是我的功能,试图利用可选链接:
function convertFixturesToArray() {
fixturesStore.getFixtures()?.api?.fixtures?.length ? fixtures.api.fixtures.map(fixture => (
//TRANSFORMATION GOES IN HERE
)) : null;
}
解决方案
你似乎在正确的轨道上。应该是这样的(用稍微现代一点的 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,
},
}) ?? [];
推荐阅读
- java - 如何使用 JAXB 返回 XML 文件
- excel - Excel - 基于多选下拉列表的 SUMIF
- css - Safari 在标签未打开时暂停 CSS 动画延迟计时器?
- python - 仅比较 Pandas DataFrame 中两列数据时间对象之间的日期
- java - 有没有更有效的方法来计算每个连续字母在字符串中出现的次数?(爪哇)
- javascript - 如何将字符串转换为数组
- python - 如何在python中的序列上下文?
- c# - 如何在其值中使用逗号将 cookie 添加到 CookieContainer c#
- c++ - 如何让构造函数接受所有类型的迭代器?
- sql - SQL 查询为 CSV 或 EXCEL 格式