如何使用串联数组创建表

新鲜色调

目前我有一个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

任何帮助是极大的赞赏!

阿克斯雅各布斯

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

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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章