Jim*_* G. 2 javascript json transformation ecmascript-6 lodash
假设我有以下JSON数组:
[
{
"team": "Colts",
"players": [
{
"name": "Andrew Luck",
"position": "quarterback"
},
{
"name": "Quenton Nelson",
"position": "guard"
}
]
},
{
"team": "Patriots",
"players": [
{
"name": "Tom Brady",
"position": "quarterback"
},
{
"name": "Shaq Mason",
"position": "guard"
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
我想将JSON转换为以下形式:
[
{
"name": "Andrew Luck",
"position": "quarterback",
"team": "Colts"
},
{
"name": "Quenton Nelson",
"position": "guard",
"team": "Colts"
},
{
"name": "Tom Brady",
"position": "quarterback",
"team": "Patriots"
},
{
"name": "Shaq Mason",
"position": "guard",
"team": "Patriots"
}
]
Run Code Online (Sandbox Code Playgroud)
如何使用ES6或lodash语法执行此操作?
使用简单循环(ES2015):
const players = [];
for (const team of teams) {
for (const player of team.players) {
players.push(Object.assign({team: team.team}, player));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用对象传播,而不是Object.assign如果您的环境支持它。
使用Array#flatMap(将正式成为ES2019的一部分,或使用lodash):
const players = teams.flatMap(
team => team.players.map(player => {...player, team: team.team})
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |