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

133
Visualizações
loop through each li and store values into multidimensional array using javascript / jQuery

I have a HTML list. I want to loop through each li and store the text in an array. My final array should be as below :

[{
  text: ["country", "city", "poste code", "address", "name", "surname", "email", "tel number"],
  textwithBrackets: ["[country]", "[city]", "[poste code]", "[address]", "[name]", "[surname]", "[email]", "[tel number]"]
}]

What I did was :

1- loop through each li using map and return the text to an array 1

2- do the same step as the first but returning each text with brackets to an array 2

3- create a final array and pushing both array 1 and array 2 by key / value

Below is my code. It's working but is there any better solution using jQuery I am not aware of ? how can I do both map in one step for example and assign the merge into the final array directly ?

Thank you very much for your suggestions.

var liText = $('ul > li').map(function(){ return $(this).text(); }).get();

var liTextwithBrackets = $('ul > li').map(function(){ return '[' + $(this).text() + ']'; }).get();


var result = [];
result.push({
  text: liText, 
  textwithBrackets: liTextwithBrackets });
        
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>country</li>
  <li>city</li>
  <li>poste code</li>
  <li>address</li>
  <li>name</li>
  <li>surname</li>
  <li>email</li>
  <li>tel number</li>
</ul>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Kindly try this. Its a bit performant than your approach.

var liText = $('ul > li').map(function() {return $(this).text();}).get();
var result = [{
  text: liText,
  textwithBrackets: liText.map(val => '[' + val + ']')
}];
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>country</li>
  <li>city</li>
  <li>poste code</li>
  <li>address</li>
  <li>name</li>
  <li>surname</li>
  <li>email</li>
  <li>tel number</li>
</ul>

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