如何过滤两个数组获取关联对象,将对应产品归入所属分类?
实现方案
你可以通过先构建分类ID映射表的方式高效完成数据组装,避免频繁遍历分类数组,JavaScript实现代码如下:
完整代码
// 初始化分类映射表与带products字段的分类结果数组 const categoryIdMap = {} const categoriesProducts = categories.map(category => { const formattedCategory = { ...category, products: [] } categoryIdMap[category.id] = formattedCategory return formattedCategory }) // 遍历产品列表,将产品推入对应分类 productsList.forEach(product => { // 提取需要存入的产品字段,可按需扩展 const productBaseInfo = { id: product.id, name: product.name } // 遍历产品所属的所有分类匹配对应项 product.categories.forEach(belongCategory => { const targetCategory = categoryIdMap[belongCategory.id] targetCategory && targetCategory.products.push(productBaseInfo) }) }) // 【可选操作】如果需要过滤掉无关联产品的分类,执行以下代码 const result = categoriesProducts.filter(item => item.products.length)
运行后得到的result数组就是你要求的输出结构。
内容的提问来源于stack exchange,提问作者Oliver D
相关产品推荐
相关产品推荐

