0

I am using node.js as server language and Mysql as database so I am running query and getting data from database but is is showing in format like this

  [ BinaryRow { name: 'Dheeraj', amount: '77.0000' },
    BinaryRow { name: 'Raju', amount: '255.0000' } ]

What I want is

    ['Dheeraj', 77.0000],
    ['Raju', 66255.000030],

This what I am doing in my backend (node.js):

My model:

static getChartData(phoneNo, userType) {

        let sql = 'select businessname as name,sum(billamt) amount from cashbackdispdets where consphoneno =' + phoneNo + ' group by  businessid order by tstime desc limit 10'
        return db.execute(sql, [phoneNo]);

My controller:

exports.getColumnChart = function(req, res) {
    const phoneNo = req.body.userId
    const userType = req.body.userType
    console.log(phoneNo)
    dashboardModule.getChartData(phoneNo, userType)
        .then(([rows]) => {
            if (rows.length > 0) {
                console.log(rows)
                return res.json(rows)
            } else {
                console.log("error")
                return res.status(404).json({ error: 'Phone No. already taken' })
            }
        })
    .catch((error) => {
        console.log(error)
        return res.status(404).json({ error: 'Something went wrong !!' })
    })
}

I am sending this data to Ui and when I am receiving it on UI it is in the form of object inside array which is not the required data type I want

axios().post('/api/v1/Dashboard/DashboardColumnChart',this.form)
  .then(res=>{
    console.log(res.data)
    debugger
  this.chartData= res.data
       })

The above code consoles on browser like this

I am not getting any idea how o do it should I do it with backend or with front end and how

6
  • Use an ORM (Object Relational Mapping) library called Sequelize for this purpose. It will make querying and receiving data much simpler. Commented Nov 4, 2019 at 8:26
  • @HussainNawazLalee can you help me with a little example please Commented Nov 4, 2019 at 8:44
  • You will have to add some boilerplate, so if you are already a long way into the project I would not recommend it but if you are just beginning you can start using this library. After you have set up sequelize in your project. Let's say you want to SELECT * FROM Products. Sequelize will have Product model defined and you can just call Product.findAll() and it will return all the products in JSON format. You also have helpful methods like incldue to get related Tables as nested objects and many other stuff that makes it easy to work with Node Commented Nov 4, 2019 at 11:02
  • As for the current use case I have added an answer that will help you format the data Commented Nov 4, 2019 at 11:09
  • Your code is also currently vulnerable to SQL injection, so I really recommend revisiting the way you are constructing your query, should this be used in prod. Commented Nov 4, 2019 at 13:39

2 Answers 2

2

Nodejs will send you a JSON response if you want to change it. It is better to change or maniuplate it in a Front end framework. But if you want to change it in backend as you have asked Make sure that the rows is in the format that you want to recive.

 let data = [ 
        { "name": "Dheeraj", "amount": "77.0000" }, 
        { "name": "Raju", "amount": "255.0000" } 
    ]
    // empty array to store the data
    let testData = [];
    data.forEach(element => {
          testData.push(element.name)
    });
Sign up to request clarification or add additional context in comments.

5 Comments

On Ui I don't have any idea how to do it(manipulation) and in backend it is coming as in object in array format
what are you using for fronend of this application. It is normal , Node js will send the response as JSON object. If you want to send in that sepecific format. use return res(rows). It will fix your problem then it will not be an object of JSON type. It will be plain response
vuejs I am using and from node i is send plain responce the it will be in form [{}] this only I want to send it like [][] this in array form above in my post I have showed, and how can I do it with front end not getting any idea
I am getting responce like this [ { "name": "Dheeraj", "amount": "77.0000" }, { "name": "Raju", "amount": "255.0000" } ] but i want ['Dheeraj', 77.0000], ['Raju', 66255.000030], this
Dear friend let me solve your question in your front end app or backend you can apply the following code . data is the response coming from the server. now we will manuplate. Check the answer I updated it for you.
0

You can format it using array.map and Object.values. map functions loops over each element and returns a modified element according to the callback provided. Object.values simply returns all the values of an object in an array.

const data = [ { "name": "Dheeraj", "amount": "77.0000" }, { "name": "Raju", "amount": "255.0000" } ];

const formattedData = data.map(obj => Object.values(obj));

console.log("Initial Data: ", data);
console.log("Formatted Data: ", formattedData);


// Map function example
const a = [1,2,3]
const mappedA = a.map(e => e * 2)
console.log(a, " mapped to: ", mappedA);

// Object.values example
const b = { firstName: 'John', lastName: 'Doe', number: '120120' }
console.log(Object.values(b));

1 Comment

You can use parseInt(string) to convert your string to a number

Your Answer

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