Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda