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

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

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