Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Covert 2D array in string to 2D array

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

Here's the "long way" to achieve what you are looking to do. I first tear the string apart by:

  1. Removing the brackets at the beginning of the string
  2. Removing the brackets at the end of the string
  3. split the array into 3 parts using data.split("],[");
  4. Loop through the array (now in 3 pieces)
  5. Create a temp string and remove single quotes
  6. Split second dimension by comma creating temp_arr
  7. 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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!