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>