newnaem ansmdae
newnaem ansmdae

Reputation: 49

get data and value from jquery array

I am trying to check if there is an id existing in an array, if the id is already there, then I will update that id's value. Otherwise I will push the id and its value into the array. How can I achieve that with jquery?

I have tried but it doesn't work, but double the size of the array

    $(itemData).each(function() {
        var name = $(this).data("name");
        var value = parseFloat($(this).data("amount"));

        if(dataArr.length == 0) {
            dataArr.push([name, value]);

        } else {
            $.each(dataArr, function(n, v) {
                if(name == n) {
                    v += value;
                }else {
                    dataArr.push([name, value]);
                }
            });
        }
    });

Upvotes: 0

Views: 62

Answers (2)

GregL
GregL

Reputation: 38151

You are close, try the following:

$(function() {
  var itemData = $('.item-data'),
    dataArr = [];

  $(itemData).each(function() {
    var name = $(this).data("name");
    var value = parseFloat($(this).data("amount"));

    var found = false;
    $.each(dataArr, function(index, val) {
      if (!found && name == val[0]) {
        val[1] += value;
        found = true;
      }
    });
    if (!found) {
      dataArr.push([name, value]);
    }
  });

  console.log('dataArray = ', dataArr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item-data" data-name="name1" data-amount="1"></div>
<div class="item-data" data-name="name2" data-amount="2"></div>
<div class="item-data" data-name="name1" data-amount="3"></div>
<div class="item-data" data-name="name2" data-amount="4"></div>
<div class="item-data" data-name="name3" data-amount="5"></div>

Upvotes: 1

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

I guess it would be easier with a hash (object literal), not an array:

var dataObj = {};
$(itemData).each(function() {
        var name = $(this).data("name");
        var value = parseFloat($(this).data("amount"));
        dataObj[name] = typeof dataObj[name] !== 'undefined' ? dataObj[name] + value : value;
});

Upvotes: 1

Related Questions