-2

I build a simple cart.

First I have an array of items called vouchers - like:

"[{"id":"108","name":"Gourmet Tasting Menu for Two","price":"85.00","photo":"1102/KtOdtlg.jpg"},{"id":"109","name":"Sampler Menu for Two","price":"60.00","photo":"1102/YrLaHlg.jpg"},{"id":"127","name":"£100 Gift Voucher","price":"100.00","photo":"1102/qexxflg.jpg"}]"

and cart = [];

Now I have a function to add items to CART array:

//with this function based on ID I find object into vouchers array and push that into CART array


    function addItemToCart (id) {
        qty = $('#qty').val();
        var data = $.grep(vouchers, function(e){ return e.id == id; });
        data = data[0];
        data.voucher_id = id;
        data.to = $('#to').val();
        data.from = $('#from').val();
        data.isGift = 0;
        data.recipient_email = $('#recipient_email').val();
        if (data.recipient_email != '') {
            data.isGift = 1;
        }
        data.message = $('#message').val();
        data.qty = qty;
        data.total = qty*data.price;
        cart.push(data);

    };

and this works good and add Item into the CART but also change values in vouchers array. Why? WHy data.total is added into the object in vouchers array...

I need vouchers array to be with unchangeable values... Why when I change values this way it binds values into vouchers array.

Aleks Per
  • 1,549
  • 7
  • 33
  • 68

1 Answers1

1

Simply clone any type of array with:

[].concat(data);

since concat may not work in some IE browsers, you can use this:

new_array = old_array.slice(0);

or you can use

var clonedArray = JSON.parse(JSON.stringify(originalArray))

var clonedArray = $.map(originalArray, function (obj) {
                  return $.extend({}, obj);
              });
Negi Rox
  • 3,828
  • 1
  • 11
  • 18