Issue pushing object into an array JS

Posted by Javacadabra on Stack Overflow See other posts from Stack Overflow or by Javacadabra
Published on 2014-06-11T09:21:55Z Indexed on 2014/06/11 9:24 UTC
Read the original article Hit count: 163

Filed under:
|

I'm having an issue placing an object into my array in javascript. This is the code:

$('.confirmBtn').click(function(){
    //Get reference to the Value in the Text area
    var comment = $("#comments").val();

    //Create Object
    var orderComment = {
    'comment' : comment
    };

    //Add Object to the Array

    productArray.push(orderComment);

    //update cookie
    $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
});

However when I print the array this is the output:

Array ( [0] => Array ( [stockCode] => CBL202659/A [quantity] => 8 ) [1] => Array ( [stockCode] => CBL201764 [quantity] => 6 ) [2] => TEST TEST )

I would like it to look like this:

Array ( [0] => Array ( [stockCode] => CBL202659/A [quantity] => 8 ) [1] => Array ( [stockCode] => CBL201764 [quantity] => 6 ) [2] Array( [comment] => TEST TEST )

I added products to the array in a similar way and it worked fine:

var productArray = []; // Will hold order Items

$(".orderBtn").click(function(event){
        //Check to ensure quantity > 0
        if(quantity == 0){
            console.log("Quantity must be greater than 0")
        }else{//It is so continue
            //Show the order Box
            $(".order-alert").show();
            event.preventDefault();

            //Get reference to the product clicked
            var stockCode = $(this).closest('li').find('.stock_code').html();
            //Get reference to the quantity selected
            var quantity = $(this).closest('li').find('.order_amount').val();

            //Order Item (contains stockCode and Quantity) - Can add whatever data I like here
            var orderItem = {
            'stockCode' : stockCode,
            'quantity'  : quantity
            };

            //Check if cookie exists 
            if($.cookie('order_cookie') === undefined){
            console.log("Creating new cookie");
            //Add object to the Array
            productArray.push(orderItem);

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about arrays