如何使用串联数组创建表

问题描述

当前我有一个btn,该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","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

非常感谢您的帮助!

解决方法

您可以做的就是在创建带有成分名称和数量的对象之后,创建一个遍历所有对象的新循环并创建trtd

const ingredientsResults = [
    {
        dinnerName: "Vegetable Soup",ingredients: ["potatoes","onion","spring onion","lentils","beans","turnip" ]
    },{
        dinnerName: "Spaghetti",ingredients: ["spaghetti pasta","tomato box","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>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...