0

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

1 Answer 1

0

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I also think there are faster / more concise ways, but it works perfectly ! Thanks a lot for the quick reply! +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.