let data = [
{size: 1180160, category: "Keswick", index: 1},
{size: 1059328, category: "HCOPA", index: 2},
{size: 30720, category: "HCOPA", index: 3},
{size: 493056, category: "Darhan Saluja", index: 4},
{size: 267776, category: "CRSA", index: 5},:
{size: 328704, category: "Arundel", index: 6}
{size: 73216, category: "Arundel", index: 7}
data.forEach((product, index) => {
let count = 0;
if (product.category !== lastCategory) {
rows.push(
<ProductCategoryRow
category={product.category}
key={product.category}/>
);
}
rows.push(
<ProductRow
product={product}
key={product.name} count={count}/>
);
lastCategory = product.category;
});
我想要计算具有相同类别的计数(数量)。如果它们属于同一类别,则数量将增加。因此,它将作为道具传递给组件
答案 0 :(得分:0)
您可以使用Array.prototype.reduce:
执行此操作const counts = data.reduce((counts, product) => {
counts[product.category] = (counts[product.category] || 0) + 1
return counts
}, {})
// counts = {Arundel: 2, ...}
比创建你的元素:
let rows = []
data.forEach(product => {
rows.push(<ProductCategoryRow category={product.category} key={product.category}>)
rows.push(<ProductRow product={product} key={product.name} count={counts[product.categort]} />
})
答案 1 :(得分:0)
试试这个:
let dataArray = [
{size: 1180160, category: "Keswick", index: 1},
{size: 1059328, category: "HCOPA", index: 2},
{size: 30720, category: "HCOPA", index: 3},
{size: 493056, category: "Darhan Saluja", index: 4},
{size: 267776, category: "CRSA", index: 5},
{size: 328704, category: "Arundel", index: 6},
{size: 73216, category: "Arundel", index: 7}
]
var d = dataArray.reduce(function (Objects, data, index) {
console.log(Objects)
if (data.category in Objects) {
Objects[data.category]++;
}
else {
Objects[data.category] = 1;
}
dataArray[index].counts = Objects[data.category];
return Objects;
}, {});
console.log(dataArray)