0

My aim is to list all ingredients for a product. Unfortunately there are multiple ingredient arrays, with multiple ingredients inside each array. The amount of arrays will vary product to product so I need someway to capture all ingredients. So far I have:

Finds all ingredient arrays and lists them separately

$(function() {
    var params = {
        // Request parameters
        // "gtin": "{string}",
       // "tpnb": "{string}",
       // "tpnc": "{string}",
       // "catid": "{string}",

        // "gtin": "05052004435789",
            "tpnc": "285363525",
    };

    $.ajax({
        url: "https://dev.tescolabs.com/product/?" + $.param(params),
        beforeSend: function(xhrObj){
            // Request headers
            xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","key");
        },
        type: "GET",
        // Request body
        data: "{body}",

    })
        .done(function(data) {
            // alert("success");
            // alert(data);
            console.log(data);

var ingredientArrays = data.products[0].ingredients;
var l = ingredientArrays.length;
for (i = 0; i < l; i++){
   var allIngredients = ingredientArrays[i];
    console.log(allIngredients);
}

        })
        .fail(function() {
            alert("error");
        });
});

Lists ingredients of a single defined ingredient array, in this case array 2.

var list = data.products[0].ingredients[2];
var ingredient = list.split(/[:;,.]+/);
for (list = 0; list < ingredient.length; ++list) {
    console.log(ingredient[list]);
}

So far so good, but I wish to merge this functionality so that I can find all ingredients within all arrays and create one single list.

If I do console.log(data); I get:

enter image description here

{
  "products": [{
    "gtin": "05054402006097",
    "tpnb": "073706172",
    "tpnc": "285363525",
    "description": "Tesco Stonebaked Thin Double Pepperoni Pizza 330G",
    "brand": "TESCO",
    "qtyContents": {
      "quantity": 330.0,
      "totalQuantity": 330.0,
      "quantityUom": "g",
      "netContents": "330g e"
    },
    "productCharacteristics": {
      "isFood": true,
      "isDrink": false,
      "healthScore": 48,
      "isHazardous": false,
      "storageType": "Frozen"
    },
    "ingredients": [
      "<strong>Wheat</strong> Flour",
      "Tomato Purée",
      "Mozzarella Cheese (<strong>Milk</strong>) (16%), Pepperoni (10%), Water, Mini Pepperoni (3.5%), Yeast, Dextrose, Rapeseed Oil, Salt, Sugar, Dried Garlic, Dried Herbs, Spice. Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Antioxidants (Extracts of Rosemary, Sodium Ascorbate), Preservative (Sodium Nitrite). Mini Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Sugar, Antioxidants (Sodium Erythorbate, Extracts of Rosemary), Preservative (Sodium Nitrite)."
    ],

UPDATE

To clarify, I can return results in console log like this:

tesco.js:70 
["<strong>Wheat</strong> Flour"]
0
:
"<strong>Wheat</strong> Flour"
length
:
1
__proto__
:
Array(0)
tesco.js:70 
["Tomato Purée"]
0
:
"Tomato Purée"
length
:
1
__proto__
:
Array(0)
tesco.js:70 
(35) ["Mozzarella Cheese (<strong>Milk</strong>) (16%)", " Pepperoni (10%)", " Water", " Mini Pepperoni (3", "5%)", " Yeast", " Dextrose", " Rapeseed Oil", " Salt", " Sugar", " Dried Garlic", " Dried Herbs", " Spice", " Pepperoni contains", " Pork", " Pork Fat", " Salt", " Dextrose", " Spices", " Spice Extracts", " Antioxidants (Extracts of Rosemary", " Sodium Ascorbate)", " Preservative (Sodium Nitrite)", " Mini Pepperoni contains", " Pork", " Pork Fat", " Salt", " Dextrose", " Spices", " Spice Extracts", " Sugar", " Antioxidants (Sodium Erythorbate", " Extracts of Rosemary)", " Preservative (Sodium Nitrite)", ""]
0
:
"Mozzarella Cheese (<strong>Milk</strong>) (16%)"
1
:
" Pepperoni (10%)"
2
:
" Water"
3
:
" Mini Pepperoni (3"
4
:
"5%)"
5
:
" Yeast"
6
:
" Dextrose"
7
:
" Rapeseed Oil"
8
:
" Salt"
/// and so on\

With this code:

    var ingredientArrays = data.products[0].ingredients;
    var l = ingredientArrays.length;
    for (i = 0; i < l; i++){
       var allIngredients = ingredientArrays[i];
        var ingredient = allIngredients.split(/[:;,.]+/);
        console.log(ingredient);
    }

But as you can see it counts the ingredients separately. I would like them to be one complete list. The count should start at 0 and go up. Instead of displaying the results based on each ingredient array, whereby I get the above result of 1, 1, 35. I would instead get one result of 37.

Dan
  • 951
  • 1
  • 23
  • 46
  • Please share a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) i.e: Content of object `data`. – Ele Feb 04 '18 at 00:39
  • I have updated my question and added a screen shot which covers this. – Dan Feb 04 '18 at 00:43
  • 1
    no it does not covers this , you need to click on the link provided to atlest read what it says – Muhammad Omer Aslam Feb 04 '18 at 00:44
  • and if possible post the sample array that you are showing in the picture as text inside your post that will provide you more quick responses for the solution – Muhammad Omer Aslam Feb 04 '18 at 00:46
  • Ok I have updated again and think I have included all you could need. Sorry I didnt think that it may be necessary to see more than I had initially provided. – Dan Feb 04 '18 at 00:50
  • thats ok you will know these things with time, now tell me that the `ingredients` contents could vary and you want to iterate all of them, is that all? – Muhammad Omer Aslam Feb 04 '18 at 00:59
  • that is correct. the number of ingredient arrays in this case is 3 but this is not necessarily going to be the same for every product, and the number of ingredients in total for each of the ingredient arrays will vary also. – Dan Feb 04 '18 at 01:02
  • sorry if i am wrong, you mean there could be 2 indexes with the name `ingredients`? I don't think you mean to say that – Muhammad Omer Aslam Feb 04 '18 at 01:05
  • no sorry, there will only be one index called `ingredients`. Within that there will be a varying number of arrays. In this case 3 but in other cases maybe more or less. And within each of those there will be varying numbers of ingredients. For example in array 1 in this case there is just 1 (tomato puree) but in array 2 there are lots. – Dan Feb 04 '18 at 01:09
  • arrays within `ingredients` i maybe should have said – Dan Feb 04 '18 at 01:10
  • added an answer see if that helps – Muhammad Omer Aslam Feb 04 '18 at 01:11
  • updated my answer see the **EDIT** section – Muhammad Omer Aslam Feb 04 '18 at 01:55

1 Answers1

1

So as your actual problem is that you want to iterate the response received from the server and that response can have multiple products and inside each of those products you have ingredients array and the size of that array can vary and you want to be able to iterate all the indexes inside it.

You should use for in and for loop. To see difference see here.

I will use the provided response data and iterate over it and it will iterate all the products and all the ingredients inside it.

See a demo below

var response = {
  "products": [{
    "gtin": "05054402006097",
    "tpnb": "073706172",
    "tpnc": "285363525",
    "description": "Tesco Stonebaked Thin Double Pepperoni Pizza 330G",
    "brand": "TESCO",
    "qtyContents": {
      "quantity": 330.0,
      "totalQuantity": 330.0,
      "quantityUom": "g",
      "netContents": "330g e"
    },
    "productCharacteristics": {
      "isFood": true,
      "isDrink": false,
      "healthScore": 48,
      "isHazardous": false,
      "storageType": "Frozen"
    },
    "ingredients": [
      "<strong>Wheat</strong> Flour",
      "Tomato Purée",
      "Mozzarella Cheese (<strong>Milk</strong>) (16%), Pepperoni (10%), Water, Mini Pepperoni (3.5%), Yeast, Dextrose, Rapeseed Oil, Salt, Sugar, Dried Garlic, Dried Herbs, Spice. Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Antioxidants (Extracts of Rosemary, Sodium Ascorbate), Preservative (Sodium Nitrite). Mini Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Sugar, Antioxidants (Sodium Erythorbate, Extracts of Rosemary), Preservative (Sodium Nitrite)."
    ],
  }]
}
//console.log(test.products);
let products = response.products;
for (var data in products) {
  let product = products[data];
  let ingredients = product.ingredients;
  console.log("PRODUCT : " + product.brand);
  console.log("=======================");
  console.log("INGREDIENTS");
  for (var i = 0; i < ingredients.length; i++) {

    console.log("--------------" + ingredients[i]);
  }
  console.log("=======================");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

EDIT

As after your update it is actually that you are splitting each index inside the ingredients array on a regex i.e /[:;,.]/ and the resulting indexes of the array can vary and for all those arrays after splitting you want to be merged into a single array so you need to use Array.prototype.concat()

see a demo below

var test = {
  "products": [{
    "gtin": "05054402006097",
    "tpnb": "073706172",
    "tpnc": "285363525",
    "description": "Tesco Stonebaked Thin Double Pepperoni Pizza 330G",
    "brand": "TESCO",
    "qtyContents": {
      "quantity": 330.0,
      "totalQuantity": 330.0,
      "quantityUom": "g",
      "netContents": "330g e"
    },
    "productCharacteristics": {
      "isFood": true,
      "isDrink": false,
      "healthScore": 48,
      "isHazardous": false,
      "storageType": "Frozen"
    },
    "ingredients": [
      "<strong>Wheat</strong> Flour",
      "Tomato Purée",
      "Mozzarella Cheese (<strong>Milk</strong>) (16%), Pepperoni (10%), Water, Mini Pepperoni (3.5%), Yeast, Dextrose, Rapeseed Oil, Salt, Sugar, Dried Garlic, Dried Herbs, Spice. Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Antioxidants (Extracts of Rosemary, Sodium Ascorbate), Preservative (Sodium Nitrite). Mini Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Sugar, Antioxidants (Sodium Erythorbate, Extracts of Rosemary), Preservative (Sodium Nitrite)."
    ],
  }]
}

var ingredientArrays = test.products[0].ingredients;
var l = ingredientArrays.length;
var merged = Array();
for (i = 0; i < l; i++) {
  var allIngredients = ingredientArrays[i];
  var ingredient = allIngredients.split(/[:;,.]+/);
  // merged.push(Array.prototype.concat.apply([], ingredient));
  merged = merged.concat(ingredient);
}

console.log(merged);
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
  • Thank you @Muhammad Omer Aslam. However my existing code can pretty much do the same thing. I have added further code to my question to evidence where I am at currently and try to explain the better the result I wish to achieve. – Dan Feb 04 '18 at 01:33
  • I included the regex stuff in initial question but appreciate I could have explained what result I had and what I wanted a little better. Your EDIT response with the `Array.prototype.concat() ` is exactly the result I was looking for. Thank you for sticking with me :) – Dan Feb 04 '18 at 02:03
  • :) thats ok brother you are welcome. @Dan i did noticed the `regex` but didnt knew that you want the splitted arrays to be re-indexed – Muhammad Omer Aslam Feb 04 '18 at 02:05