如何遍历数组矩阵并按类别生成包含商品的对象
按类别归类矩阵中的商品对象
原始数据
const productMatrix = [ [ { category: 'tech', product: "iPhone X", price: 320 }, { category: 'food', product: "Cheerios", price: 5 }, ], [ { category: 'food', product: "Snickers", price: 1.5 }, { category: 'tech', product: "Air Pods", price: 129 }, ], ];
现有遍历函数
function sortProducts (matrix) { for (x=0;x<matrix.length;x++) { for (y=0;y<matrix[x].length;y++){ console.log(matrix[x][y]); } } }
修改后的归类实现
要实现按类别归类并返回目标结构,你可以在遍历过程中维护一个结果对象,根据每个商品的category属性将其添加到对应数组中:
function sortProducts(matrix) { // 初始化结果对象 const categorizedProducts = {}; for (let x = 0; x < matrix.length; x++) { for (let y = 0; y < matrix[x].length; y++){ const product = matrix[x][y]; // 如果当前类别不存在,先创建空数组 if (!categorizedProducts[product.category]) { categorizedProducts[product.category] = []; } // 将商品添加到对应类别的数组中 categorizedProducts[product.category].push(product); } } return categorizedProducts; } // 调用示例 const result = sortProducts(productMatrix); console.log(result);
输出结果
运行后会得到符合要求的结构:
{ tech: [ { category: 'tech', product: 'iPhone X', price: 320 }, { category: 'tech', product: 'Air Pods', price: 129 } ], food: [ { category: 'food', product: 'Cheerios', price: 5 }, { category: 'food', product: 'Snickers', price: 1.5 } ] }
补充说明
- 给循环变量
x和y加上let声明,避免污染全局变量 - 每次处理商品时先检查类别是否已存在,不存在则初始化空数组,再推入商品对象
内容的提问来源于stack exchange,提问作者Niko Nota
相关产品推荐
相关产品推荐

