如何遍历两个对象数组,生成含productCount属性的新分类数组?
问题:基于产品数组统计分类产品数量,生成带计数的分类数组
现有两个对象数组:
const products = [ { brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Tees', }, ]; const categories = [ { name: 'Jeans', }, { name: 'Tees', }, ];
需要生成包含productCount属性的新分类数组(注:按现有数据,Tees的实际产品数应为1,示例期望中的0可能是笔误,以下代码按真实统计逻辑实现):
const newCategories = [ { name: 'Jeans', productCount: 2, }, { name: 'Tees', productCount: 1, }, ];
你尝试的代码无法实现需求,问题出在:
findIndex仅能找到第一个匹配产品的索引,无法统计所有符合条件的产品总数count++仅执行一次,只会将0变为1,没有累加所有匹配项的数量
正确解决方案
方案一:先统计计数再映射(性能更优)
先遍历一次产品数组,统计每个分类的产品数量,再映射到分类数组上,适合大数据量场景:
// 统计各分类的产品数量 const categoryCountMap = {}; products.forEach(product => { const categoryName = product.category; // 若分类已存在则计数+1,否则初始化为1 categoryCountMap[categoryName] = (categoryCountMap[categoryName] || 0) + 1; }); // 生成带计数的新分类数组 const newCategories = categories.map(category => ({ ...category, // 从统计map中取对应数量,无则设为0 productCount: categoryCountMap[category.name] || 0 }));
方案二:直接在map中统计(简洁直观)
在map遍历分类时,用filter筛选对应分类的产品并取长度,适合小数据量场景:
const newCategories = categories.map(category => ({ ...category, productCount: products.filter(product => product.category === category.name).length }));
内容的提问来源于stack exchange,提问作者qweezz
相关产品推荐
相关产品推荐

