Joachim Vanthuyne
Joachim Vanthuyne

Reputation: 355

Javascript push Array items in Object

I have the following issue for creating a object in Javascript

When a user clicks a button I want to push the sn_slab to the array slabs. But each serial_number is grouped by the batch_number.

The object should look something like this

    var Object = {
    'COFBP21018': {
        slabs: {
            0: 18765,
            1: 38947,
            ...
        }
    },
    'DEPOUS394O': {
        slabs: {
            0: 11006276,
            1: 11020446,
                    ...

        }
    },
    ..
}

my html looks like this

<a href=".." class="add_slab_to_array" data-batch_nr="COFBP21018" data-sn_slab="18765" />
<a href=".." class="add_slab_to_array" data-batch_nr="COFBP21018" data-sn_slab="38947" />
<a href=".." class="add_slab_to_array" data-batch_nr="DEPOUS394O" data-sn_slab="11006276" />
<a href=".." class="add_slab_to_array" data-batch_nr="DEPOUS394O" data-sn_slab="11020446" />

var block = {};
$('.add_slab_to_array').click(function(event) {
        event.preventDefault();

        var batch_nr = $( this ).attr('data-batch_nr');
        var sn_slab = $( this ).attr('data-sn_slab');

        // Create new object if batch_nr does not exists
        // ADD sn_slab to Array inside the Object with related batch_nr

      block[batch_nr] = {
           slabs: [],
           add: function(sn_slab) {
               this.slabs.push(sn_slab)
           }
       }

       block[batch_nr].add(sn_slab);

 });

The code above works, but my array slabs is always overridden.

Upvotes: 0

Views: 98

Answers (2)

Consider this

     block[batch_nr] = {
       slabs: [],
       add: function(sn_slab) {
           if (block[batch_nr]) {
               block[batch_nr].slabs.push(sn_slab)
           }
       }
   }

Upvotes: 0

ffflabs
ffflabs

Reputation: 17481

It seems to me you're redefining the block object each time you click. You should instead check if it's set before proceeding.

block[batch_nr] = block[batch_nr] || {};

block[batch_nr].slabs = block[batch_nr].slabs || [];

block[batch_nr].add = block[batch_nr].add || function(sn_slab) {                         
            this.slabs.push(sn_slab);
           };

Upvotes: 2

Related Questions