Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda