0

Quick edit - I am a complete beginner in web development, so I realize the solution might be stupidly obvious.

I'm attempting to insert a data set into a MySQL db through nodejs/expressjs/mysql.

I have a successful connection to the db and can query from it without issues.

Here is my post code:

app.post('/pyme', function(req,res){
    console.log("Data being POSTED to db...");
    var post = req.body;
    console.log(post);
    var sql_insert_pyme = 'INSERT INTO pyme(NombreComercio,NumeroTelefono) VALUES =?';
    sql.query(sql_insert_pyme,post,function(err){
    if(err) throw err;
    });
});  

The POST data I am getting looks as follows:

{ NombreComercio: 'Sebastian Avila',
  NumeroTelefono: '71021714' }

I need a method to break that post into a simple:

"'Sebastian Avila', '71021714'"

Basically I want to end with:

post = "'Sebastian Avila', '71021714'"

2 Answers 2

1

You need to reduce a JSON object to an array (you can reduce it to string straight away, but array gives you more control over) and join it.

var postObject = {
    NombreComercio: 'Sebastian Avila',
    NumeroTelefono: '71021714'
}

var postArray = Object.keys(postObject).reduce(function(reduced, jsonKey) {
    reduced.push("'" + postObject[jsonKey] + "'");
    return reduced;
}, []);

var postString = postArray.join(',');

console.log(postString);

If you want query parameters to be dynamic, you can as well set Object.keys(postObject).join(',') in columns names part of the query.

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

2 Comments

This solved it. Thanks! I was running around in circles figuring out how to reduce and push the object
You're welcome. Simple stuff and now you know how to handle it. Cheers!
0

Try this

 var postObject = {
NombreComercio: 'Sebastian Avila',
NumeroTelefono: '71021714'
}

var vals = Object.keys(postObject).map(function(key) {
return "'"+postObject[key]+"'";
});

console.log(vals.join(','))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.