Ad

'for' Loop In Array Push (javascript)

- 1 answer

I have a syntax problem, I am trying to integrate go.pl analytics to cart in shopify so the final code will look like this:

var goadservicesq = goadservicesq || [];
goadservicesq.push(
  [
    "_BASKET",
    [
      // first position in basket
      {
        identifier: '35353635535',
        quantity: '2'
      },
      // second position in basket
      {
        identifier: '55353533378566',
        quantity: '1'
      },
      // last position in basket
      {
        identifier: '458457435643464',
        quantity: '3'
      },
      // extra product which solves the "comma" problem 
      {}
    ]
  ]
);

and here I am trying to make "for" loop inside to have a final result like above:

// trying to make "for" loop
$.getJSON( "/cart.js", function( data ) {
  console.log(data);
  
  // user.go.pl CART script
  var goadservicesq = goadservicesq || [];
  goadservicesq.push(
    [
      "_BASKET",
      [
                      
        for (var i = 0; i < data.items_count; i++) {  
          {
            identifier: data.items[i].id,
            quantity: data.items[i].quantity
          }, 
        } 
              
        // extra product which solves the "comma" problem 
        {}
      ]
    ]
  );
});

it throws an error ->http://prntscr.com/ci7jpz Please help me.

Ad

Answer

You need to build up the basket array outside of the literal array:

// trying to make "for" loop
$.getJSON( "/cart.js", function( data ) {
    console.log(data);
    // user.go.pl CART script
    var basket = [];
    for (var i = 0; i < data.items_count; i++) {
        basket.push({
            identifier: data.items[i].id,
            quantity: data.items[i].quantity
        });
    }
    var goadservicesq = goadservicesq || [];
    goadservicesq.push( [ "_BASKET", basket ] );
});
Ad
source: stackoverflow.com
Ad