【发布时间】:2020-09-15 19:04:25
【问题描述】:
我正在努力解决这个问题。
我正在开发一个带有条形码扫描仪的拣货应用程序。我有一个多步骤表格,一次显示一个产品。用户可以选择该项目并转到下一个或跳过它,因为它没有库存。 我现在有这个对象数组,是在提交表单后获得的。它显示用户输入的代码并使用产品的 id 验证它(我创建了 id)。如果 code: "" 为空,是因为用户跳过了它。
[
{
"orderid": "12696",
"id": 3929,
"name": "Eucaliptus 90 Gr",
"quantity": 3,
"code": "3929"
},
{
"orderid": "12696",
"id": 3929,
"name": "Eucaliptus 90 Gr",
"quantity": 3,
"code": "3929"
},
{
"orderid": "12696",
"id": 3929,
"name": "Eucaliptus 90 Gr",
"quantity": 3,
"code": ""
},
{
"orderid": "12696",
"id": 2739,
"name": "Hellmanns 232 Ml",
"quantity": 4,
"code": "2739"
},
{
"orderid": "12696",
"id": 2739,
"name": "Hellmanns 232 Ml",
"quantity": 4,
"code": "2739"
},
{
"orderid": "12696",
"id": 2739,
"name": "Hellmanns 232 Ml",
"quantity": 4,
"code": ""
},
{
"orderid": "12696",
"id": 2739,
"name": "Hellmanns 232 Ml",
"quantity": 4,
"code": ""
}
]
我正在寻找总数,同一产品有多少物品被选中,哪些没有。
这是我需要的一个例子:
[
{
"orderid": "12696",
"id": 3929,
"name": "Eucaliptus 90 Gr",
"quantity": 3,
"picked": 2,
"notPicked": 1
},
{
"orderid": "12696",
"id": 2739,
"name": "Hellmanns 232 Ml",
"quantity": 4,
"picked": 2,
"notPicked": 2
}
]
提前致谢!
这是我的代码:
// Here i grab all the code inputs, even empty ones
const totalItemsPickedArr = req.body.code;
//I convert that array of codes into an array of objects
let newTotalItemsArr = totalItemsPickedArr.map(code => {
return ({
code
})
})
// I bring all the items from the order via sequelize
db.Detallepedido.findAll({
where: {
pedido_id: orderid
},
include: [{ all: true, nested: true }],
order: [['productoorden', 'orden', 'ASC']]
})
.then(products => {
// Here i map the promise and make a new array of objects with the data i need.
let productListArr = products.map(product => {
return ({
orderid: orderid,
id: product.producto_id,
name: product.producto_nombre,
price: product.precio,
quantity: product.cantidad,
order: product.productoorden.orden,
category:
product.productoorden.categoriaproducto[0].categoria_id,
})
})
// Flattened makes each object multiply by its quantity, so it returns a bigger array, like the one i showed in the first array.
const flattened = productListArr.reduce((acc, item) => {
return [
...acc,
...Array.from({ length: item.quantity }, () => ({...item}))
]
}, [])
//then i make a new array with the flattened array and I paste the code the user input.
let newProductListArr = flattened.map((product, index) => {
return ({
...product,
...newTotalItemsArr[index]})
})
在我展平数组后,我只需要为每个产品显示一个对象,并根据输入的代码添加已选择/未选择的总数。
对不起,如果它太复杂了,我知道这不是最好的代码。谢谢!
【问题讨论】:
-
到目前为止你尝试了什么?
-
@limido 我试过reduce,但我不知道如何根据属性“code”是否为空来获取总数。
-
请将您的代码添加到问题中,以便我们为您提供指导
-
@limido 我编辑并添加了代码
标签: javascript node.js sequelize.js