javascript - 当它们具有相同的类别时,如何计算每个项目的数量?
问题描述
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;
});
我想计算具有相同类别的计数(数字)。如果它们属于同一类别,数量将增加。所以这将作为道具传递给组件
解决方案
尝试这个:
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)
推荐阅读
- grails - 无法使用 Java 11 运行 Grails 4.0.1 cli - 在堆栈跟踪中出现空指针错误
- c# - 双斜杠在字符串 C# 中无法正常工作
- angular - app.module.ts 中声明的 Angular 子 html 引用组件
- codeblocks - 我需要在 Code::Blocks 中更改工作区的颜色
- c# - 有没有办法在 c# 中将参数与访问器一起使用
- python - 如何正确使用 Keras 添加层?
- go - 从其他功能使用 mongodb 连接
- sql - SQL:从两列lat,long_更新新列作为几何点
- arrays - lua :将值存储在字符串数组中并通过调用随机索引打印值
- java - 如何使我的方法更加面向对象?