I have 2 arrays ingredients and measures in my margaritas object and I'm trying to render a list of ingredients to the dom where ingredients[0] is an ingredient and measures[0] is the measure of the ingredient, and so on. I cannot figure out how to make this work and I'm wondering if maybe i need to restructure my code or if i'm making a mistake somewhere.
The code is here at: https://jsfiddle.net/morjman/m4ucy0t7/3/
When I tried to do it I created a renderIngredients function which takes 2 arrays and a parent element but I think that's wrong as well
why not use a regular good old array iteration? Assuming ingredients and measures have the same array elements, you can do sth like this,
for(let i = 0; i< measures.length; i++){
//Do stuff on ingredients[i];
//Do some other stuff with measures[i];
}
Make sure they have equal number of items or else you'll end up pointing to null.
Like someone else mentioned, you can use a for loop:
let numIngredients = margarita.ingredients.length;
let strIngredients = '';
for(let i = 0; i < numIngredients; i++) {
let ing = margarita.ingredients[i] || '';
let meas = margarita.measures[i] || '';
strIngredients += '<li>' + ing + " " + meas + '</li>'
}
const html = `
<div class="margarita-details">
<h2><span>${margarita.id}</span> ${margarita.name}</h2>
<ul>${strIngredients}</ul>
<img src="${margarita.img}" alt="${margarita.imgAlt}" />
<p class="instructions">${margarita.instructions}</p>
<p class="">${margarita.isAlcoholic ? "Contains Alcohol!!" : ""}</p>
</div>
`;
There are two ways you can do this. But for both methods, arrays should be in equal length.
First method is the most classic way.
for(let i = 0; i< measures.length; i++){
ingred = ingredients[i]
measure = measures[i]
// do something
}
The second way to do it is zip both arrays first and then iterate.
var zipped = ingredients.map(function(e, i) {
return [e, measures[i]];
});
// zipped = [[ingred1,mes1],[ingred2,mes2],[ingred3,mes3],.....]
// Then iterate through the zipped array
And there are several other methods to zip arrays in js. refer this