Shazboticus S Shazbot Shazboticus S Shazbot - 1 year ago 87
Javascript Question

Javascript table string to array

I have a string that looks like:


...which is of course essentially a table.

I'd like to dynamically convert this string into an array containing 2 arrays. One of dates, one of values.

[Edited in]
An array of objects with date and values would work too.

Answer Source

The following::

var input = // your string

var output = $(input).slice(1).map(function(i,el) {
    var tds = $(el).find("td");
    return { "date" : tds.eq(0).text(), "value" : tds.eq(1).text() };

...will return an array of objects in this format:

[{"date":"2013-01-01","value":"231.198"}, {"date":"2013-02-01","value":"232.770"}, ... ]

If you'd like each value to be treated as a number you can convert it like so:

    return { "date" : tds.eq(0).text(), "value" : +tds.eq(1).text() };
    // add the unary plus operator ---------------^

Then the result will be:

[{"date":"2013-01-01","value":231.198}, {"date":"2013-02-01","value":232.77}, ... ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download