如何递归遍历对象数组并筛选生成扁平化新数组?
嵌套分类数组扁平化(仅保留name和code字段)的多种实现方案
我有如下嵌套对象数组:
[ { "id": "11ed-a261-0242ac120002", "name": "Languages", "code": 1, "description": "Here you can find teacher for any language. Learn when you want and how you want.", "childrenCategories": [ { "id": "a261-0242ac120002", "name": "German", "code": 7, "description": "Here you can find teacher for German. Learn when you want and how you want.", "childrenCategories": [] }, { "id": "a261-0242ac120002", "name": "Spanish", "code": 8, "description": "Here you can find teacher for Spanish. Learn when you want and how you want.", "childrenCategories": [] } ] }, { "id": "a261-0242ac120002", "name": "Sciences", "code": 3, "description": "It is your online university. Learn whatever you want and become better.", "childrenCategories": [ { "id": "6a66915a-3439-11ed-a261-0242ac120002", "name": "Mathematics", "code": 12, "description": "It is your online university. Learn Mathematics and become better.", "childrenCategories": [] }, { "id": "6a669420-3439-11ed-a261-0242ac120002", "name": "Physics", "code": 13, "description": "It is your online university. Learn Physics and become better.", "childrenCategories": [] } ] } ]
需要生成仅包含name和code字段的扁平化数组:
[ {"name": "Languages", "code": 1}, {"name": "German", "code": 7}, {"name": "Spanish", "code": 8}, {"name": "Sciences", "code": 3}, {"name": "Mathematics", "code": 12}, {"name": "Physics", "code": 13} ]
我已经实现了一个可行方案:
const flatten = (arr) => { let result = [] arr.flatMap((item) => { result.push({name: item.name, code: item.code}) item.childrenCategories.map(child => result.push({name: child.name, code: child.code}) ) }) return result }
以下是其他几种不同的实现方案:
方案1:递归实现(支持任意层级嵌套)
如果后续分类可能出现更深层级的嵌套,递归方案能通用处理所有深度的子分类:
const flattenCategories = (categories) => { let result = [] categories.forEach(category => { // 添加当前分类的核心字段 result.push({ name: category.name, code: category.code }) // 递归处理子分类并合并结果 if (category.childrenCategories.length > 0) { result = result.concat(flattenCategories(category.childrenCategories)) } }) return result }
方案2:reduce+concat组合(非递归,适配两层嵌套场景)
利用reduce累加结果,结合concat一次性合并当前项和所有子项:
const flatten = (arr) => { return arr.reduce((acc, item) => { return acc.concat( { name: item.name, code: item.code }, item.childrenCategories.map(child => ({ name: child.name, code: child.code })) ) }, []) }
方案3:flatMap链式调用(简洁写法)
充分利用flatMap自动扁平化数组的特性,直接返回当前项和子项的数组集合:
const flatten = (arr) => { return arr.flatMap(item => [ { name: item.name, code: item.code }, ...item.childrenCategories.map(child => ({ name: child.name, code: child.code })) ]) }
方案4:生成器函数(迭代式扁平化)
生成器函数可以逐个输出分类项,适合处理大数据量时降低内存占用:
function* generateFlatCategories(categories) { for (const category of categories) { yield { name: category.name, code: category.code } // 迭代子分类 yield* generateFlatCategories(category.childrenCategories) } } // 使用时转换为数组 const flatten = (arr) => Array.from(generateFlatCategories(arr))
内容的提问来源于stack exchange,提问作者Vasyl
相关产品推荐
相关产品推荐

