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>
-
2Reading DOM is relatively slow. So you could run the first map, then use map on the first array to generate the second (rather than re-read ul>li .text)fdomn-m– fdomn-m2022年02月02日 14:13:51 +00:00Commented Feb 2, 2022 at 14:13
1 Answer 1
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>