【发布时间】:2020-11-10 20:59:09
【问题描述】:
目前我有一个 btn,它调用如下函数:
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)
},{})
};
这会从一堆数组中获取信息,如下所示:
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"]
}
];
单击按钮时,它会将 [Object, object] 返回到“resultsDiv”。我研究了如何将其放入带有连接结果的列表/表格中,但我发现的唯一东西是 JSON.stringify( ) 这给了我一堆废话!这是有原因的还是我错过了什么?我主要想在表格/列表中显示结果
我想要的结果如下:
{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
非常感谢任何帮助!
【问题讨论】:
-
您的按钮调用的函数没有意义,特别是
return (document.getElementById("resultsDiv").innerText = acc)看起来您正在尝试计算重复的成分。你的意图是什么,你期望什么输出? -
我的意图是获得一个包含项目列表的输出,并且有重复项,例如 onions: 2 etc..
-
如果您在问题中模拟您的预期输出将会很有帮助。
-
您想要的回报是第一列中的成分名称和第二列中的数量吗?
-
是的,这基本上就是我想要达到的目标:)
标签: javascript html-table stringify