我有一个应该返回一个数组的API,但是我的结果是每个数组都有3个以上的对象,因此我需要对其进行映射,并在后端进行了操作
async function getAllProduct(req,res) {
try {
const results = await Products.findAll({
// raw: true, <= remove
attributes:['id','name', 'float', 'price'],
include: [{
model: SubCategory,
as: 'subcategory',
attributes: ['id','name'],
},
{
model:Exteriors,
as: 'exteriors',
attributes: ['id','name']
},
{
model:Types,
as: 'types',
attributes: ['id','name']
},
],
})
results.map( (products) => {
const model = {
id: products.id,
name: products.name,
float: products.float,
price: products.price,
id_sub: products.subcategory.id,
subcategory: products.subcategory.name,
id_types: products.types.id,
type: products.types.name,
id_ext: products.exteriors.id,
exterior: products.exteriors.name,
}
listProducts.push(model);
})
if(listProducts){
return res.status(200).json({listProducts})
}
else{
return res.status(400).json({result: 'failed to get Products'})
}
} catch (error) {
console.error(error);
}
}
最好将结果映射到前端或已经发送了映射,如何缩小此路径以从前端获取数据