Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove quotation marks from values in JavaScript Array Object

I am trying to get my JSON encoded array formatted properly. Here is my PHP MySQL Query:

$query = "SELECT date, value1, value2
            FROM testdata
            ORDER BY date ASC";  


         $result = mysql_query($query);
         $myChartData = array();
          while($row = mysql_fetch_assoc($result)){
            $myChartData[] = $row;
                        }

   <script type="text/javascript">
    var chartData = <?php echo json_encode($myChartData); ?>;

From the console, the object looks like this:

[Object { date="2011-02-23", value1="133034", value2="12105.78"},
 Object { date="2011-02-24", value1="122290", value2="12068.50"},
 Object { date="2011-03-08", value1="453142", value2="12214.38"}]

The quotation marks around the date stays, but the ones on value1 and value2 need to be stripped out.

Self-teaching noob at all of this...Thanks for your help!

like image 620
EotS Avatar asked Jul 16 '26 16:07

EotS


2 Answers

First:

The quotation marks around the date stays, but the ones on value1 and value2 need to be stripped out.

There are no quotation marks! What you see as a visual representation of the data contained in chartData. In this case it is an array with three objects, each having three properties containing strings.
What you want is to convert some of these strings into numbers (integers, floating point).


The correct way

It seems you are not storing the data correctly in your DB. If the values were numbers, they would be encoded as such.

The only reasonable solution is to fix it at that end. That means you have to define the data types of your DB fields properly.


The workaround

If, for some reason, you cannot fix the DB (you should try really hard), you have the possibility to convert the strings to numbers

  • in PHP, using intval [docs] and/or floatval [docs]
  • or in JavaScript with the unary plus operator [docs]:

    var number = +string;
    

If you are new to JavaScript, you might want to read Working with Objects [MDN] first.

like image 140
Felix Kling Avatar answered Jul 18 '26 06:07

Felix Kling


A simple javascript solution:

function formatChartData(data) {
    for(var i = 0, length = data.length; i < length; i++) {
        data[i].value1 = parseInt(data[i].value1, 10);
        data[i].value2 = parseFloat(data[i].value2);
    }
    return data;
}

var chartData = formatChartData(<?php echo json_encode($myChartData); ?>);
like image 23
Joe Avatar answered Jul 18 '26 06:07

Joe