将对象值的Javascript数组转换为多维数组
我正在使用NodeJS学习expressJS.
I am in process of learning expressJS with NodeJS.
我正在尝试在mySQL表中插入多行.由于批量插入查询需要
I am trying to insert multiple rows into mySQL table. Since the bulk insert query requires data like
[["a",1], ["b",2], ["c",3]]
如何将对象数组转换为这种形式?这是我的JSON发布数据
How can I transform my array of objects to such form? Here is my JSON post data
[
{
"productID" : 1,
"stock": -3
},
{
"productID" : 1,
"stock": 5
}
]
如何将此类JSON对象转换为多维数组?
How to tranform such JSON object into the multidimensional array?
[[1,-3],[1,5]]
这是到目前为止我尝试过的.
Here is what I have tried so far.
let promises = []
req.body.map((n) => {
promises.push(new Promise(resolve => {
let { productID, stock } = n
let values = {
PRODUCT_ID: productID,
STOCK: stock
}
let sql = 'INSERT INTO product_stock_history SET ?'
db.connection.query(sql, values, (err, results) => {
if (err) {
console.log("Failed to add stocks record: " + err)
res.sendStatus(500)
return
} else {
res.send("Stock record has been added")
}
})
}))
})
上面的代码可以正常工作,但是最后我在mySQL语法上有错误,我认为这与Promise有关.我对诺言不熟悉:)
The above code is working, but in the end I have error with the mySQL syntax which I believe something to do with the promise. I am not familiar with the promise :)
Error: Can't set headers after they are sent.
所以我要实现的只是没有Promise的映射.
So what i want to achieve is just the mapping without Promise.
谢谢
您可以传递 map
像这样:
You could pass Object.values
as parameter to map
like this:
const input = [
{
"productID" : 1,
"stock": -3
},
{
"productID" : 1,
"stock": 5
}
]
const output = input.map(Object.values)
console.log(output)