Javascript - 重构数组 - 数组减少
Javascript - refactor array - array reduce
重构数组/对象数组的最佳方法是什么?
我正在考虑使用 array.reduce,但找不到解决方案。
例如,转换这个数组:
const carsInput =
[
{
brand: 'volkswagen',
model: 'golf',
motorSpec: {
...
},
Dim: {
...
},
},
...
{
brand: 'volkswagen',
model: 'passat',
motorSpec: {
...
},
Dim: {
...
},
},
]
到这个对象数组
const carsOutput =
{
volkswagen: {
brandName: 'volkswagen',
models: {
golf: {
modelName: 'golf',
motorSpec: {
...
},
Dim: {
...
},
},
passat: {
modelName: 'passat',
motorSpec: {
...
},
Dim: {
...
},
},
},
},
}
此外,如果您想到另一种(更好的)方式来呈现这一系列对象,我会洗耳恭听!
非常感谢
我相信其他人有更简洁的方法来做到这一点,但这里是一种方法。
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)
重构数组/对象数组的最佳方法是什么? 我正在考虑使用 array.reduce,但找不到解决方案。
例如,转换这个数组:
const carsInput =
[
{
brand: 'volkswagen',
model: 'golf',
motorSpec: {
...
},
Dim: {
...
},
},
...
{
brand: 'volkswagen',
model: 'passat',
motorSpec: {
...
},
Dim: {
...
},
},
]
到这个对象数组
const carsOutput =
{
volkswagen: {
brandName: 'volkswagen',
models: {
golf: {
modelName: 'golf',
motorSpec: {
...
},
Dim: {
...
},
},
passat: {
modelName: 'passat',
motorSpec: {
...
},
Dim: {
...
},
},
},
},
}
此外,如果您想到另一种(更好的)方式来呈现这一系列对象,我会洗耳恭听! 非常感谢
我相信其他人有更简洁的方法来做到这一点,但这里是一种方法。
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)