RedGiant
RedGiant

Reputation: 4748

Using map function to get lists' data attributes into an array in jQuery

Working example

Fail example

I'm using this pie chart plugin. I want to create an array like this

            [["Male",12,"some text","#222"],
            ["Female",14,"some text","#333"]]

from li data attributes data-value, each of which stores a comma-separated string:

<ul> 
 <li data-value="12 or below,6,sometext,red">12 or below</li>
 <li data-value="13 or above,19,sometext,yellow">13 or above</li>
</ul>

I'm not getting any error but the map function isn't returning an array as the pie chart isn't showing anything. Would anyone show me how to return an array from the lists?

Failed Code

function chart(stats){
   new Chart.Pie('age', {
   showTooltips : true, 
   chartMinSize : [200, 200], 
   chartMaxSize : [250, 250], 
   chartData :  stats
   });
}    

var arr = [],
    stats = $('.piearea').find('li').map(function()    
            {
               var value = $(this).each(function(){
                   arr =  [$(this).data('value').split(',')];
            })
    return value;
});       
console.log(stats);

chart(stats);

HTML:

   <div class="piearea">
    <div id='age' class='myChart' style='position:relative;width:250px;height:250px;'></div>
     <ul>
       <li data-value="12 or below,6,sometext,red">12 or below
       </li><li data-value="13 or above,19,sometext,yellow">13 or above</li>
    </ul>
   </div>

Upvotes: 0

Views: 937

Answers (2)

Plaid Phantom
Plaid Phantom

Reputation: 83

Your map call should just be:

$('.piearea li').map(function() {
    return [$(this).data('value').split(',')];
});       

The inner .each() call is your problem: $(this) will only return a jQuery object with one item, and you are trying to use app to return out of it but you never use the variable again.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

There are 2 problems.

  1. The use of .map() is not proper
  2. The color should be hexa value(haven't used the said plugin so don't know if there is a way to make color names to work)

function chart(stats) {
  new Chart.Pie('age', {
    showTooltips: true,
    chartMinSize: [200, 200],
    chartMaxSize: [250, 250],
    chartData: stats
  });
}

var arr = [],
  stats = $('.piearea li').map(function() {
    return [$(this).data('value').split(',')];
  }).get();
console.log(stats);
console.log(JSON.stringify(stats));

chart(stats);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://article-sharing.com/pie.js"></script>
<div class="piearea">
  <div id='age' class='myChart' style='position:relative;width:250px;height:250px;'></div>
  <ul>
    <li data-value="12 or below,6,sometext, #222">12 or below</li>
    <li data-value="13 or above,19,sometext, #333">13 or above</li>
  </ul>
</div>

Upvotes: 1

Related Questions