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!
CodePudding user response:
Here's the "long way" to achieve what you are looking to do. I first tear the string apart by:
- Removing the brackets at the beginning of the string
- Removing the brackets at the end of the string
- split the array into 3 parts using
data.split("],["); - Loop through the array (now in 3 pieces)
- Create a temp string and remove single quotes
- Split second dimension by comma creating
temp_arr - Push final result of second dimension to
final_arr
var 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);
CodePudding user response:
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);
