0

我正在用 NodeJS 学习 expressJS。

我正在尝试将多行插入到 mySQL 表中。由于批量插入查询需要像这样的数据

[["a",1], ["b",2], ["c",3]]

如何将我的对象数组转换为这种形式?这是我的 JSON 帖子数据

[
 {
    "productID" : 1,
    "stock": -3
 },
 {
    "productID" : 1,
    "stock": 5
 }
]

如何将这样的 JSON 对象转换为多维数组?

[[1,-3],[1,5]]    

这是我到目前为止所尝试的。

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 语法有错误,我认为这与承诺有关。我不熟悉承诺:)

Error: Can't set headers after they are sent.

所以我想要实现的只是没有 Promise 的映射。

谢谢

4

1 回答 1

3

您可以像这样传递Object.values参数map

const input = [
 {
    "productID" : 1,
    "stock": -3
 },
 {
    "productID" : 1,
    "stock": 5
 }
]

const output = input.map(Object.values)
console.log(output)

于 2019-01-22T09:16:50.440 回答