Reputation: 3
I have a string variable which I have defined as:
var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],";
I am also using some javascript code which takes values in an array and draws a line graph out of those values.Part of the code is as shown below.
var graphData = [{
data: [[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],],
color: '#77b7c5',
points: { radius: 4, fillColor: '#77b7c5' }
}
];
I am trying to replace the data in the array with the variable I defined above but the graph is not working when I do so. This is my code:
var graphData = [{
data: [regn],
color: '#77b7c5',
points: { radius: 4, fillColor: '#77b7c5' }
}
];
Where I am going wrong or how am I supposed to get the data in my string to that array?
Upvotes: 0
Views: 100
Reputation: 236
var parseRegn = function (regnStr) {
var pairs = regnStr.split('],['), // 1
pairStr = '';
for (var i = 0; i < pairs.length; i++) {
pairStr = pairs[i].replace(/[^\d|,]/g, ''); // 2
if (pairStr.length > 0) {
pairs[i] = pairStr.split(',', 2); // 3
}
}
return pairs; // 4
};
Upvotes: 0
Reputation: 1230
In place of
var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],"
try this,
var regn=[[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67]];
var graphData = [{
data: regn,
color: '#77b7c5',
points: { radius: 4, fillColor: '#77b7c5' }
}
];
Upvotes: 0
Reputation: 26132
Alternative version with regexp parsing:
var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],";
var rez = [];
var regex = /\[(\d+),(\d+)\]/g;
var match;
while ((match = regex.exec(regn)) != null) {
rez.push([match[1], match[2]]);
}
graphData.data = rez;
Upvotes: 0
Reputation: 11822
You need to parse the string first. This is usually done using JSON.parse
:
var regn="[[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67]]";
var arr = JSON.parse(regn) // now it's an Array
If you need to support browsers that don't support JSON.parse
you can patch this using JSON3
Aside: In addition to that please notice that regn has a stray trailing comma and needs to be wrapped in a []
or {}
(the object approach would also need keys then, so the array is the way to go here), so it's not valid JSON the way you have posted it (don't know if this happened by accident or not).
Upvotes: 4