Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6: How do I unravel inner arrays and flatten the JSON array?

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?

like image 204
Jim G. Avatar asked Dec 13 '25 08:12

Jim G.


1 Answers

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})
);
like image 116
Felix Kling Avatar answered Dec 15 '25 21:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!