Currently i have a btn which calls a function as follows:
function ingredientsList() { const allIngredients = [].concat(...ingredientsResults.map(obj => obj.ingredients)) allIngredients.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1 return (document.getElementById("resultsDiv").innerText = acc) },{}) };
this gets information from a bunch of arrays as follows:
const ingredientsResults = [ { dinnerName: "Vegetable Soup", ingredients: ["potatoes", "onion", "spring onion", "lentils", "beans", "turnip" ] }, { dinnerName: "Spaghetti", ingredients: ["spaghetti pasta", "tomato box","tomato box", "onion", "sundried tomatoes", "tomato paste", "lentils"] }, { dinnerName: "Fiskebolle", ingredients: ["box of fiskebolle", "box of fiskebolle", "potatoes", "brocolli", "carrots"] } ];
when the button is clicked it returns [Object, object] back to the “resultsDiv”.I have researched how to put this either in a list / table with the concatinated results but the only thing i find is JSON.stringify() and that gives me a bunch of nonsense! Is there a reason for this or am i missing something? i primarily want to display the results in a table / list
my desired results are something as follows:
{potatoes: 2, onion: 2, spring onion: 1, lentils: 2, beans: 1, …} beans: 1 box of fiskebolle: 2 brocolli: 1 carrots: 1 lentils: 2 onion: 2 potatoes: 2 spaghetti pasta: 1 spring onion: 1 sundried tomatoes: 1 tomato box: 2 tomato paste: 1 turnip: 1
Any help is greatly appreciated!
Advertisement
Answer
Something you can do is after creating the object with the name of the ingredient and the quantity, it is creating a new loop going through all the objects and creating the tr
and td
const ingredientsResults = [ { dinnerName: "Vegetable Soup", ingredients: ["potatoes", "onion", "spring onion", "lentils", "beans", "turnip" ] }, { dinnerName: "Spaghetti", ingredients: ["spaghetti pasta", "tomato box","tomato box", "onion", "sundried tomatoes", "tomato paste", "lentils"] }, { dinnerName: "Fiskebolle", ingredients: ["box of fiskebolle", "box of fiskebolle", "potatoes", "brocolli", "carrots"] } ]; function ingredientsList() { const allIngredients = [].concat(...ingredientsResults.map(obj => obj.ingredients)) const result = allIngredients.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1 return acc // change this },{}) // add this const table = document.querySelector('#myTable') Object.keys(result).forEach(dname => { const tr = document.createElement('tr') const td1 = document.createElement('td') const td2 = document.createElement('td') td1.innerText = dname td2.innerText = result[dname] tr.append(td1) tr.append(td2) table.append(tr) }) // end }; ingredientsList()
<table id="myTable"> </table>