How to add commas for all iterations except the last iteration to an array of objects.

Scenario:

We have to create an array of objects, which stores details of each item added to the cart as an object, so the number of the object will equal the number of items in the cart, so we need to put ” , ” symbol in ending of objects but no ” , ” added in the ending.

For the above scenario, we can use this code:

Code snippet:

for (var i = 0; i < itemVal.length; i++) {
  var itemA = itemVal[i];
  itemAmt = itemA.get('amount');
  itemUrl = itemA.get('item').get('_url');
  SKU = itemA.get('item').get('itemid');
  itemName = itemA.get('item').get('displayname');
  desc = itemA.get('item').get('storedisplayname2');
  category = itemA.get('itemtype');
  other = itemA.get('item').get('urlcomponent');
  quantity = itemA.get('quantity');
  unitP = itemA.get('rate');
  totalItemP = itemA.get('total');
  if (itemA.get('item').get('itemimages_detail').urls) {
    imageUrl = itemA.get('item').get('itemimages_detail').urls[0].url ? itemA.get('item').get('itemimages_detail').urls[0].url : 'N/A';
  } else {
    imageUrl = "";
  }
  url += '{' +
    '"sku": "' + SKU + '",' +
    '"name": "' + itemName + '",' +
    '"description": "' + desc + '",' +
    '"category": "' + category + '",' +
    '"other": "' + other + '",' +
    '"unitPrice": ' + unitP + ',' +
    '"salePrice": ' + unitP + ',' +
    '"quantity": ' + quantity + ',' +
    '"totalPrice": ' + totalItemP + ',' +
    '"imageUrl": "' + imageUrl + '",' +
    '"productUrl": "' + itemUrl + '"' +
    ' }';
  //For adding comma for all iteration expect the last iteration.
  if (i !== itemVal.length - 1) {
    url += ',';
  }
}

Leave a comment

Your email address will not be published. Required fields are marked *