I feel stupid for asking this question. I have a 2D array in a string like this:
var data = "[['a', 'b', 'c'],['d', 'e', 'f'],['x', 'y', 'z']]";
and I'm trying to convert it to
var dimensional_array = [['a', 'b', 'c'],['d', 'e', 'f'],['x', 'y', 'z']];
Any help would be appreciated. Thank you all!
If you trust the string contained in data to represent a JavaScript array, you could evaluate it using the Function constructor, i.e. in your case:
var dimensional_array = Function(`return(${data})`)();
Since this is intrinsically an unsafe operation (similarly to eval), it should not be used if the contents of data could be potentially controlled by an external source (like user input, the result of an API call, etc.).
Also note that some websites block the use of the Function constructor with content security policy headers.
var data = "[['a', 'b', 'c'],['d', 'e', 'f'],['x', 'y', 'z']]";
var dimensional_array = Function(`return(${data})`)();
console.log(dimensional_array);
Here's the "long way" to achieve what you are looking to do. I first tear the string apart by:
data.split("],[");temp_arrfinal_arrvar data = "[['a', 'b', 'c'],['d', 'e', 'f'],['x', 'y', 'z']]";
data = data.substring(2);
data = data.slice(0, -2);
const dimensional_array = data.split("],[");
const final_arr = [];
for (let i = 0; i < dimensional_array.length; i++) {
var temp_string = dimensional_array[i];
temp_string = temp_string.replace(/'/g, "");
const temp_arr = temp_string.split(", ");
final_arr.push(temp_arr);
}
console.log(final_arr);