如何优化JavaScript中嵌套对象的数据提取与扁平化处理
优化嵌套对象扁平化与去重方案
核心思路
利用Set自动去重的特性,结合reduce方法一次性遍历所有产品,同时收集品牌、分类和属性的唯一值,避免多层无意义的循环嵌套,提升代码效率和可读性。
实现代码
const products = [ { "brand": "xyz", "category": "T-shirt", "attributes": [ { "name": "color", "attribute_values": [{"value": "blue"}, {"value": "green"}] }, { "name": "size", "attribute_values": [{"value": "18"}] } ] }, { "brand": "abc", "category": "footwear", "attributes": [ { "name": "color", "attribute_values": [{"value": "black"}] }, { "name": "size", "attribute_values": [{"value": "42"}, {"value": "18"}] } ] } ]; // 使用reduce一次性处理所有数据 const { brands, categories, attributeMap } = products.reduce((acc, product) => { // 收集唯一品牌 acc.brands.add(product.brand); // 收集唯一分类(统一转为小写,匹配目标格式) acc.categories.add(product.category.toLowerCase()); // 处理属性 product.attributes.forEach(attr => { // 若当前属性未在映射中,初始化一个Set存值 if (!acc.attributeMap.has(attr.name)) { acc.attributeMap.set(attr.name, new Set()); } // 将当前属性的所有值加入Set自动去重 attr.attribute_values.forEach(item => { acc.attributeMap.get(attr.name).add(item.value); }); }); return acc; }, { brands: new Set(), categories: new Set(), attributeMap: new Map() }); // 将Set转为数组,整理成目标格式 const formattedBrands = Array.from(brands); const formattedCategories = Array.from(categories); const formattedAttributes = Array.from(attributeMap.entries()).map(([name, values]) => ({ [name]: Array.from(values) })); console.log('brands =', formattedBrands); console.log('category =', formattedCategories); console.log('attributes =', formattedAttributes);
代码优势
- 单一遍历:通过
reduce只遍历一次产品数组,相比多层map减少了冗余迭代 - 自动去重:用
Set和Map天然实现去重,无需手动判断重复值 - 清晰结构:将数据收集和格式整理分离,逻辑更易维护
- 性能优化:避免了原代码中无意义的多层
map(map本身是用来转换数组,而非遍历执行副作用)
输出结果
brands = ['xyz', 'abc'] category = ['t-shirt', 'footwear'] attributes = [{'color':['blue', 'green', 'black']}, {'size':['18', '42']}]
内容的提问来源于stack exchange,提问作者Srivatsa
相关产品推荐
相关产品推荐

