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.

12
  • Please share a Minimal, Complete, and Verifiable example i.e: Content of object data. Commented Feb 4, 2018 at 0:39
  • I have updated my question and added a screen shot which covers this. Commented Feb 4, 2018 at 0:43
  • 1
    no it does not covers this , you need to click on the link provided to atlest read what it says Commented Feb 4, 2018 at 0: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 Commented Feb 4, 2018 at 0: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. Commented Feb 4, 2018 at 0:50

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 :)
:) 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.