0

I have a textbox that contains the following -

[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 1], [6, 6]]

I need to be able to convert this to an array, in exactly the same format for a graph. The code I have tried below does not work as it does not have the square brackets inside the array.

/*****SIMPLE CHART*****/
        var flashstring = document.getElementsByName('hfMessageHistory')[0].value;

        var flash = new Array();
        flash = flashstring.split(",");

        for (a in flash) {
            flash[a] = parseInt(flash[a], 10) || 0; // Explicitly include base as per Álvaro's comment
        }

        alert(flash);

        function showTooltip(x, y, contents) {
            jQuery('<div id="tooltip" class="tooltipflot">' + contents + '</div>').css({
                position: 'absolute',
                display: 'none',
                top: y + 5,
                left: x + 5
            }).appendTo("body").fadeIn(200);
        }


        var plot = jQuery.plot(jQuery("#chartplace"),
               [{ data: [flash], label: "Messages Sent", color: "#ff6c00" }], {
                   series: {
                       lines: { show: true, fill: true, fillColor: { colors: [{ opacity: 0.05 }, { opacity: 0.15 }] } },
                       points: { show: true }
                   },
                   legend: { position: 'nw' },
                   grid: { hoverable: true, clickable: true, borderColor: '#ccc', borderWidth: 1, labelMargin: 10 },
                   yaxis: { min: 0, max: 20 }
               });

3 Answers 3

1

The string is JSON. Use JSON.parse():

var flashstring = document.getElementsByName('hfMessageHistory')[0].value;
var flash = JSON.parse(flashstring);
Sign up to request clarification or add additional context in comments.

Comments

1

Avoiding other parts of your code(not clear what you're asking), you can covert a string to an array by using the bracket([]):

var str = '[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 1], [6, 6]]'
var arr = [str];

Comments

1

Use JSON.parse:

HTML:

<input type="text" id="text1" />
<button onclick="parse()">Parse</button>

JS:

$('#text1').val('[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 1], [6, 6]]');

function parse() {
    try {
        var parsed = JSON.parse($('#text1').val());
        console.log(parsed);
    } catch (e) {
        console.log('parse failed. Check your input');
    }
 }

JSFIDDLE.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.