Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to convert string of Array of Arrays into a Javascript array of arrays?

I have an ajax request that returns a list of values like this:

"[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"

I need it to be a javascript array with numbers:

[[-5, 5, 5], [-6, 15, 15], [7, 13, 12]]

I tried to replace the '[' and ']' for a '|' and then split by '|' and foreach item split by ',' and add them to an array, but this is not elegant at all.

Do you guys have any suggestions?

like image 287
cesarferreira Avatar asked Oct 17 '13 04:10

cesarferreira


2 Answers

You can use JSON.parse() to convert that string into an array, as long as you wrap it in some brackets manually first:

var value = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var json = JSON.parse("[" + value + "]");

console.log(json);

I would suggest correcting the output at the server if possible, though.

like image 200
Marty Avatar answered Sep 17 '22 15:09

Marty


This solution is stupid in practice -- absolutely use JSON.parse as others have said -- but in the interest of having fun with regular expressions, here you go:

function getMatches(regexp, string) {
  var match, matches = [];
  while ((match = regexp.exec(string)) !== null)
    matches.push(match[0]);
  return matches;
}

function parseIntArrays(string) {
  return getMatches(/\[[^\]]+\]/g, string)
    .map(function (string) {
      return getMatches(/\-?\d+/g, string)
        .map(function (string) { 
          return parseInt(string); 
        });
    });
}

parseIntArrays("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]");
like image 41
Chris Martin Avatar answered Sep 20 '22 15:09

Chris Martin