'Parsing dynamic JSON structure in JavaScript using .map to create specific arrays?

I am looking to create a function that will iterate through JSON and fetch an ID. If there are details within the object containing the ID, attach them to that array as well.

Something like json?.cars?.map(m => 'Manufacturer.' + m?.manufacturer) retrieves the manufacturers into separate arrays, but I also wanted to retrieve the 'Model' if available and put it into the Manufacturer array so it might look like this.

[[ Manufacturer.Toyota ], Model.Supra, Model.Rav4 ]] [ Manufacturer.BMW ] [ Manufacturer.Mercedes ]

{
  'Cars': [
    {
      'Manufacturer': 'Toyota',
      'Details': [
        {
          'Model': 'Supra',
          'Transmission': 'Manual',
          'Colour': 'Red'
        },
        {
          'Model': 'Rav4',
          'Transmission': 'Automatic',
          'Colour': 'White'
        }
      ]
    },
    {
      'Manufacturer': 'BMW'
    },
    {
      'Manufacturer': 'Mercedes'
    }
  ]
}


Solution 1:[1]

Couldn't think of a easier way, but try this:

const array = Cars.map(obj => {
  return [[obj.Manufacturer], obj?.Details !== undefined ? obj.Details.map(details => details.Model) : null].filter(obj => obj !== null)
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johnni O.