遍历JS对象筛选category_2中含blue标签商品时出现重复循环问题
问题原因
- 原始数据结构书写错误:你给出的商品条目用数组符号
[]包裹了键值对,实际商品是对象类型,应该用{}包裹,语法错误会导致属性读取异常,触发你遇到的匹配、循环异常问题。 - 方法执行前未清空结果数组:如果
getCategories被多次调用,旧的匹配结果会一直累积在this.categorydata中,出现重复条目。 - 存在冗余循环逻辑:不需要遍历所有分类的key,直接读取指定分类即可,减少无意义的性能消耗。
修复步骤
1. 修正原始数据结构
const categories = { category_1: [ { id: 1, name: 'Product 1', tags: [] }, { id: 2, name: 'Product 2', tags: [] } ], category_2: [ { id: 3, name: 'Product 3', tags: [] }, { id: 4, name: 'Product 4', tags: ['blue'] }, { id: 5, name: 'Product 5', tags: [] }, { id: 6, name: 'Product 6', tags: ['blue'] } ] }
2. 修正方法代码
兼容你原有逻辑的修改版
getCategories(){ // 先清空结果数组,避免旧数据累积 this.categorydata = [] // 直接读取目标分类,不需要遍历所有分类 const target = categories['category_2'] if(!target) return target.forEach(c => { if(c.tags.includes('blue')){ this.categorydata.push(c) } }) }
更简洁的简化版(用filter直接过滤符合条件的条目)
getCategories(){ this.categorydata = (categories['category_2'] || []).filter(c => c.tags.includes('blue')) }
内容的提问来源于stack exchange,提问作者Aurilie
相关产品推荐
相关产品推荐

