1

I have a simple list.

<ul id="testCaseList" class="list-group testCaseList">
  <li class="list-group-item justify-content-between" style="">test1 (hi)</li>
  <li class="list-group-item justify-content-between" draggable="false" style="">test2 (bye)</li>
  <li class="list-group-item justify-content-between" style="">test3 (hello)</li>
</ul>

I want to create an array with of arrays. With name (type). So the result would be something like this:

[
 ["test1", "hi"] 
 ["test2", "bye"] 
 ["test3", "hello"] 
]

I'm trying something like this but I'm getting multiple errors.

var testCaseList = $('#testCaseList');
  $.each(testCaseList, function (index, item) {
    console.log(item);
    data.push(item.text());
  });
  console.log(data);

Uncaught TypeError: item.text is not a function
at HTMLUListElement. (create-flow.js:182)
at Function.each (jquery-3.2.1.min.js:2)
at a.onUpdate (create-flow.js:180)
at k (Sortable.min.js:2)
at a._onDrop (Sortable.min.js:2)
at a.handleEvent (Sortable.min.js:2)

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

2 Answers2

2

To achieve this you can use map() to build an array from the matched elements. Within the map() handler you can use a regular expression with groups to pull out the text values you require. Try this:

var arr = $('ul li').map(function() {
  var matches = /(.*) \((.*)\)/g.exec($(this).text());
  matches[0] = '';
  return [matches];
}).get();

console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="testCaseList" class="list-group testCaseList">
  <li class="list-group-item justify-content-between" style="">test1 (hi)</li>
  <li class="list-group-item justify-content-between" draggable="false" style="">test2 (bye)</li>
  <li class="list-group-item justify-content-between" style="">test3 (hello)</li>
</ul>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

@Rory McCrossan's answer is right but have updated based on your answer...

var listGroupItem = $('.list-group-item');
 var data = [];
       $.each(listGroupItem, function (index, item) {
           var string = item.innerHTML.split('(').join().split(')');
            data.push(string);
            data = data.filter(function(n){ 
            return n != "";
            });
            
      });
      console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="testCaseList" class="list-group testCaseList">
   <li class="list-group-item justify-content-between" style="">test1 (hi)</li>
   <li class="list-group-item justify-content-between" draggable="false" style="">test2 (bye)</li>
   <li class="list-group-item justify-content-between" style="">test3 (hello)</li>
</ul>
Parth Raval
  • 4,097
  • 3
  • 23
  • 36