假设我的数组是
[{id: 1,
name: "chocolate bar"},
{id:2,
name: "Gummy worms"},
{id:3,
name:"chocolate bar"}]如何在dom上显示"2个巧克力棒和1个小虫子“?
发布于 2020-12-02 22:46:30
您可以尝试如下所示:
const array = [
{
id: 1,
name: "chocolate bar"
},
{
id:2,
name: "Gummy worms"
},
{
id:3,
name:"chocolate bar"
}
];
...
const countCandy = candyName => array.filter(obj => obj.name === candyName).length
...
return (
<div>{`${countCandy("chocolate bar")} chocolate bars and ${countCandy("Gummy worms")} Gummy Worms`}<div>
)或者更通用的方法是使用reduce并返回object:
const countCandy = array.reduce((acc, cur) => {
acc[cur.name] = (acc[cur.name] || 0) + 1;
return acc;
}, {})
...
return (
<div>{Object.entries(countCandy).map((el) => `${el[1]} ${el[0]}`)}<div>
)发布于 2020-12-02 22:56:30
使用reduce()方法和Object.assign(),您可以创建一个包含计算出的重复项的新对象。
在DOM上显示它可以通过许多不同的方式来完成。我添加了一个创建它的列表项的示例。你应该能够根据你的喜好修改它。
const arr = [{
id: 1,
name: "chocolate bar"
},
{
id: 2,
name: "Gummy worms"
},
{
id: 3,
name: "chocolate bar"
}
]
//SUmmarize the source arr
const summary = arr.reduce((accumulator, item) => Object.assign(accumulator, {
[item.name]: (accumulator[item.name] || 0) + 1
}), {});
//Example how to show it on the dom, modify to your likings
for (const [k, v] of Object.entries(summary)) {
document.querySelector('#target').innerHTML += `<li>${k}: ${v}</li>`
}<ul id="target"></ul>
发布于 2020-12-02 22:47:50
var temp = {};
var array = [
{ id: 1, name: "chocolate bar" },
{ id: 2, name: "Gummy worms" },
{ id: 3, name: "chocolate bar" }
];
array.forEach(value => {
if (!this.temp[value.name]) {
this.temp[value.name] = 1;
} else {
this.temp[value.name]++;
}
});并在显示中使用temp变量
https://stackoverflow.com/questions/65110196
复制相似问题