Search code examples
javascriptarraysjsonjavascript-objects

How to get all the objects in this data model?


I need to take all the Model Objects in this kind of data structure below.

const PRODUCTS = [
    {
        brand: 'Audi',
        allSeries: {
            serie: 'A3',
            allModels: [
                { model: 'A3 1.5 Sportback' },
                { model: 'A3 2.0 TDI' }
            ]
        }
    },
    {
        brand: 'Volkswagen',
        allSeries: {
            serie: 'Golf',
            allModels: [
                { model: 'Golf 1.5' },
                { model: 'Golf 2.0' }
            ]
        }
    }
]

So I need all the model objects in one array pushed like [{model:'Golf 1.5}, {...}, {...}] this data structure.


Solution

  • This is simple enough to do with the array map() method. Let me know if this works for you:

    const PRODUCTS = [{ brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: 'A3 1.5 Sportback' }, { model: 'A3 2.0 TDI' } ] } },{ brand: 'Volkswagen', allSeries: { serie: 'Golf', allModels: [ { model: 'Golf 1.5' }, { model: 'Golf 2.0' } ] } }];
    
    const models = PRODUCTS.flatMap(product => product.allSeries.allModels);
    
    console.log(models);