Skip to content Skip to sidebar Skip to footer

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],

Solution 1:

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.

Solution 2:

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:

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

functionparseIntArrays(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]");

Solution 3:

If you're generating the data, and you trust it, just use eval:

varstring = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"var arrays = eval('[' + string + ']');

Alternatively, start returning well-formed JSON.

Solution 4:

In a function

var strToArr = function(string){ returnJSON.parse('[' + string + ']')}

console.log(strToArr("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"));

Solution 5:

varstring = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var arr = [];
var tmp = string.split('], ');

for (var i=0; i<tmp.length; i++) {
    arr.push(tmp[i].replace(/\[|\]/g, '').split(', '));
}

Typing on my iPad so I apologize in advance for any typos.

Post a Comment for "Elegant Way To Convert String Of Array Of Arrays Into A Javascript Array Of Arrays?"