refactoringarrayobjectarray-reduce

Javascript - refactor array - array reduce


What is the best way to refactor(ise) an array / array of objects ? I was thinking of using array.reduce, but could not figure out a solution.

for example, transform this array :

const carsInput =
     [
        {
            brand: 'volkswagen',
            model: 'golf',
            motorSpec: {
                ...
            },
            Dim: {
                ...
            },
        },
...
        {
            brand: 'volkswagen',
            model: 'passat',
            motorSpec: {
                ...
            },
            Dim: {
                ...
            },
        },
    ]

to this array of objects

const carsOutput =
    {
        volkswagen: {
            brandName: 'volkswagen',
            models: {
                golf: {
                    modelName: 'golf',
                    motorSpec: {
                       ...
                    },
                    Dim: {
                       ...
                    },
                },
                passat: {
                    modelName: 'passat',
                    motorSpec: {
                        ...
                    },
                    Dim: {
                        ...
                    },
                },
            },
        },
    }

Also if you think of another (better) way of presenting this array of objects, I am all ears ! Thanks a lot


Solution

  • I am sure others have more concise ways of doing this but here is one approach.

    const carsInput =
         [{
                brand: 'ford',
                model: 'mustang',
                motorSpec: {
                },
                Dim: {
                }
            },
            {
                brand: 'volkswagen',
                model: 'golf',
                motorSpec: {
                },
                Dim: {
                }
            },
            {
                brand: 'volkswagen',
                model: 'passat',
                motorSpec: {
                },
                Dim: {
                }
            },
        ];
        
    const carsOutput = new Object();
    
    function initializeMake(makeName) {
      carsOutput[makeName] = { brandName: makeName, models: {}};
      return carsOutput[makeName]
    }
    
    carsInput.forEach(car => {
        let make = carsOutput[car.brand] || initializeMake(car.brand);
    
        const modelDefinition = { 
        'modelName': car['model'],
        'motorSpec': car.motorSpec,
        'Dim': car.Dim
      };
      
        make.models[car.model] = modelDefinition;
    });
    
    console.log(carsOutput)