Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading