将对象值的Javascript数组转换为多维数组 [英] Javascript Array of object value into multidimensional array

查看:85
本文介绍了将对象值的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.

谢谢

推荐答案

您可以传递

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)

这篇关于将对象值的Javascript数组转换为多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆