SO - 16117262

by Arun P Johny

HTML

Product 1: <button id="product1">Add one</button>
<br>
Product 2: <button id="product2">Add one</button>
    
<div></div>

JavaScript

var cart = new Array();

$(document).ready(function(){
    
    $('button').on('click', function() {
        var pid = $(this).attr('id');
        
        cart[cart.length] = {id:pid, qty:1}
        
        var result = {};
        cart.forEach(function(obj, index){
            if(!result[obj.id]){
                result[obj.id] = { qty: 0 }
            }
            result[obj.id].qty += obj.qty;
        });

        console.log(result)
    });
});