Fernando Urban Fernando Urban - 2 years ago 78
CSS Question

How I can separate and collect different values in a list of attributes in HTML with Javascript?

I have the next list:

<li class="list" data="Paul" data-id="2">Paul</li>
<li class="list" data="Paul" data-id="4">Paul</li>
<li class="list" data="Peter" data-id="3">Peter</li>
<li class="list" data="Peter" data-id="1">Peter</li>
<li class="list" data="John" data-id="11">John</li>
<li class="list" data="John" data-id="12">John</li>

So, the goal is get:

Paul: 6 | Peter: 4 | John: 23

I'm trying with a .map in jquery like:

$(function() {
var total = 0;
var counter = $('li.list').length;

var dataList = $("li.list").map(function() {
var data = $(this).attr('data')
return data+$(this).data("id");

mydata = dataList.join(";");

And this is returning:


How can I sort and sum for separte for get:

Paul: 6 | Peter: 4 | John: 23

Thank you.

Answer Source

You could create Array with Array.from() and use reduce and return Object

var result = Array.from($('ul li')).reduce((obj, e) => {
  obj[$(e).data('name')] = (obj[$(e).data('name')] || 0) + parseInt($(e).data('id'));
  return obj;
}, {})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <li class="list" data-name="Paul" data-id="2">Paul</li>
  <li class="list" data-name="Paul" data-id="4">Paul</li>
  <li class="list" data-name="Peter" data-id="3">Peter</li>
  <li class="list" data-name="Peter" data-id="1">Peter</li>
  <li class="list" data-name="John" data-id="11">John</li>
  <li class="list" data-name="John" data-id="12">John</li>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download