0

I am in process of learning expressJS with NodeJS.

I am trying to insert multiple rows into mySQL table. Since the bulk insert query requires data like

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

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
 }
]

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")
      }
    })
  }))
})

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.

So what i want to achieve is just the mapping without Promise.

thanks

1
  • Hi, thank you so much for the input! :) I have edited the question with codes that I have tried. Sorry for the inconvenience caused Commented Jan 22, 2019 at 9:20

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.