lel lel - 23 days ago 9
Javascript Question

Json response to array javascript

I want to convert my ajax json response into javascript array. I am not sure how i am able to do this. I tried split but it's not what i wanted. Please do help!

My AJAX Json response (This is in one string):

Array[Date:"[['2016-09-09',162], ['2016-12-04',145], ['2017-01-11',130]]"]


My desire outcome after pushing it in array:

var array = [['2016-09-09',162], ['2016-12-04',145], ['2017-01-11',130]];

Answer Source

Use regex to extract data from the string.

var str = `Array[Date:"[['2016-09-09',162], ['2016-12-04',145], ['2017-01-11',130]]"]`;

// regex for your string pattern
var re = /\[\s?'(\d{4}-\d{1,2}-\d{1,2})'\s?,\s?(\d+)\s?\]/g;
// array for result
var res = [],
  // variable for caching match
  m;

// iterate over the matches
while (m = re.exec(str)) {
  //push values into array
  res.push([m[1], +m[2]]); // use + prefix to convert into number
}

console.log(res);

Regex explanation here