Web Design
Web Design

Reputation: 105

How create two dimensional associative array in jquery?

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.

Upvotes: 0

Views: 153

Answers (2)

jcubic
jcubic

Reputation: 66498

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>

Upvotes: 1

Jamiec
Jamiec

Reputation: 136114

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>

Upvotes: 0

Related Questions