Imagine that I have the following JSON array:
[
{
"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"
}
]
}
]
And I want to transform and flatten the JSON to be the following:
[
{
"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"
}
]
How would I do this with either ES6 or lodash syntax?
With simple loops (ES2015):
const players = [];
for (const team of teams) {
for (const player of team.players) {
players.push(Object.assign({team: team.team}, player));
}
}
You can use object spread instead of Object.assign if your environment supports it.
With Array#flatMap (will officially be part of ES2019, or use lodash):
const players = teams.flatMap(
team => team.players.map(player => {...player, team: team.team})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With