0

I want to create two dimensional array with jQuery and get following result:

Array(
  [data_name_1] => Array([0] => A, [1] => B)
  [data_name_2] => Array([0] => P, [1] => L) 
  [data_name_3] => Array([0] => K, [1] => M) 
)

The HTML is

<li data-attr-name="data_name_1">
   <div class="_container_">
       <span>A</span>
       <span>B</span>
   </div>
</li>
<li data-attr-name="data_name_2">
   <div class="_container_">
      <span>P</span>
      <span>L</span>
   </div>
</li>

for first array I use following code, but for second array (test) I don't know how should I continue. The jQuery(this).data('attr-name') creates data_name_1, data_name_2 and ...

var object_name = {};
  jQuery('li').each(function(){
   object_name[jQuery(this).data('attr-name')] = 'test';
  });

Please help me. Thanks.

2
  • You need to show your html, from where those A B came from? Commented Oct 7, 2020 at 12:17
  • @jcubic I edited and add HTML. Thank you May be what I use as code in jquery is false Commented Oct 7, 2020 at 12:36

2 Answers 2

1

All you need to do is to find all spans elements with jQuery::find and get the text from that span using jQuery::text.

Map will iterate over your selected spans and jQuery::get will return array of strings from jQuery object.

var object_name = {};
$('li').each(function(){
  var li = $(this);
  object_name[li.data('attr-name')] = li.find('span').map(function() {
    return $(this).text();
  }).get();
});

console.log(object_name);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li data-attr-name="data_name_1">
   <div class="_container_">
       <span>A</span>
       <span>B</span>
   </div>
</li>
<li data-attr-name="data_name_2">
   <div class="_container_">
      <span>P</span>
      <span>L</span>
   </div>
</li>

Sign up to request clarification or add additional context in comments.

Comments

0

You can do this with the elements directly - using reduce and map as you go:

var result = $('li').get().reduce( (acc,x) => {
  acc[$(x).data("attr-name")] = $(x).find("span").get().map(s => $(s).text());
  return acc;
},{})

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li data-attr-name="data_name_1">
   <div class="_container_">
       <span>A</span>
       <span>B</span>
   </div>
</li>
<li data-attr-name="data_name_2">
   <div class="_container_">
      <span>P</span>
      <span>L</span>
   </div>
</li>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.