Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here.

My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql.

I've managed to establish a connection to the database and can query data from it with no problems.

This is the code snippet I'm working with:

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 data I receive through POST request looks like this:

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

I am looking for a way to simplify the post data into something like:

"'Sebastian Avila', '71021714'"

In other words, my goal is to transform the post data into:

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

Answer №1

To convert a JSON object into an array, you can use the reduce method and then join the elements together.

var postObject = {
    Name: 'John Doe',
    Phone: '555-1234'
}

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

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

console.log(postString);

If you need dynamic query parameters, you can also include

Object.keys(postObject).join(',') 
as part of the query's column names.

Answer №2

Give this a shot

 var customerInfo = {
FullName: 'Sebastian Avila',
PhoneNum: '71021714'
}

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the procedure for updating or adding data to a JSON file with angularJS?

After successfully creating a local JSON file and retrieving data from it using app.controller('appCtrl', function($scope, $http){ $http.get('employees.json').success(function(data){ $scope.employees=angular.fromJson(data.employee ...

What is the best way to implement multilanguage support in nodejs without relying on cookies or external modules?

Currently, I am in the process of transitioning all my projects to node.js in order to enhance my JavaScript skills. Using Node.js along with the Express module, one of my clients who runs a translation company has requested that I incorporate two language ...

Having trouble viewing the page of a new package you published on the NPM Website?

Today, I officially released an NPM package called jhp-serve. It can be easily installed using npm install or run with npx. You can even find it in the search results here: https://www.npmjs.com/search?q=jhp. However, when attempting to view its page by cl ...

I am having trouble running my project locally using npm start

Recently, I began working with ReactJS. However, I encountered an issue when trying to start the server using npm start. It seems that the start script is missing from package.json. I added the start script to the scripts section and attempted npm start, b ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

Error encountered when trying to match routes in two separate Angular applications within an Express app: "Cannot find any routes that match

Greetings (please pardon any language errors as English is not my first language) Like many others, I have an Angular app running in Express and decided to create separate Angular apps for the admin and users (mainly because the navigation bar was becomin ...

Looking for a superior option to Jersey/Jackson for constructing JSON REST APIs?

In my quest to develop the server side of a JSON-REST API, I have been experimenting with Jersey and its JSON-POJO mapping feature. However, even testing the most basic use-case has led me to seek help on various platforms and engage in extensive research. ...

Issue with AngularJS compatibility on first generation iPad

Having trouble with my first generation iPad while trying to implement a basic ngRoute and ngAnimate setup. It's working fine on desktop and iPhone 6, but not on the iPad. The error message I'm encountering is: Error[$injector:modulerr]http://e ...

Incorporate a PHP variable named "result" into a MySQL query

Is it feasible to integrate PHP data into a MySQL result? Let me elaborate: Consider two tables, one containing user actions and the other user information. By querying the actions table, I retrieve user IDs and count each one grouped by the user: $ids = ...

Converting a JSON image string (not a URL) into a UIImage to display

After spending an entire day trying to solve this, I am really desperate for an answer. It seems like a simple task - I have a JSON array of images in the form of strings (I believe). These are not URLs, but rather image file names like "GoodLogo.png". Typ ...

Securing an Express route until the request is successfully processed

My POST route performs complex operations and can take several seconds to complete. The function includes logic to prevent duplicate entity creation by checking if the data already exists in the database, which works well when requests are made sequentiall ...

Animating text with a shake effect using JQuery

I am attempting to create a shake effect on my text input field when validation fails. While I have achieved the shake effect, I am unsure how to customize the default values for direction, distance, and times. Additionally, I believe there is an error i ...

Who is the father of Bootstrap Popover?

I'm currently facing an issue with getting a popover to be placed within a specific element. As of now, the popover is being inserted directly into the <body>, but I require it to be relative to other elements. I have been unable to locate a met ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

Creating a toggle feature using ng-switch

I'm having trouble getting this code to function correctly as a toggle. Can anyone offer any suggestions on what might be causing the issue? <div ng-switch="!!myvar"> <a ng-switch-when="false" ng-click="myvar = true" style="cursor:poin ...

npm error | Module '@emotion/styled' not found

My Node project is encountering a new issue that wasn't present yesterday. The only change I can think of is an OS update the previous night on Ubuntu 20.04. Stack trace: [nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watchin ...

Encountered a difficulty in resolving the dependency flawlessly within the Next.js application

Every time I try to deploy my next.js project, I encounter the same error message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

A technique, such as regular expressions, can be used to detect the quantity of newline characters in the text entered by the user in a text area

I'm trying to figure out how to count the number of newline characters (or whatever is inserted when the user presses the return key) in a textarea's value. I believe I should be using a regular expression for this task, but I'm not very ski ...

Tips for refreshing Facebook's og tags

I've been racking my brains over this issue for days, and despite the abundance of similar inquiries, I have yet to find a solution. On my blog-like website, each post requires its own title and description for Facebook articles. I know I can set the ...

What are the steps to developing a chat application with MERN stack or another straightforward method?

What is the best way to develop a chat application for direct communication between two individuals? For instance, imagine a website with numerous producers where a consumer wishes to engage in a live chat with a specific producer. Any ideas on how to ach ...