如何使用TypeScript从嵌套对象中提取无children属性的对象的所有id值
提取嵌套对象中无children属性的id数组
当然有可行的实现方法啦!针对这种嵌套层级的对象结构,递归遍历是最直接且高效的解决方案,下面给你两种常用的实现方式:
方法一:基础递归函数实现
这种写法逻辑清晰,适合初学者理解:
const data = { id: 240, name: 'FY1 2022', children: [ { id: 241, name: 'Q1 2022', children: [ { id: 242, name: 'Jan 2022', }, { id: 243, name: 'Feb 2022', }, { id: 244, name: 'Mar 2022', }, ], }, ], }; function extractLeafIds(obj) { let ids = []; // 判断当前对象是否不包含children属性 if (!('children' in obj)) { ids.push(obj.id); } else { // 递归遍历每个子对象,合并结果 obj.children.forEach(child => { ids = ids.concat(extractLeafIds(child)); }); } return ids; } const result = extractLeafIds(data); console.log(result); // 输出: [242, 243, 244]
代码说明:
- 函数
extractLeafIds接收目标对象作为参数,初始化空数组用于收集id - 如果当前对象没有
children属性,就将它的id加入数组 - 如果存在
children,则遍历每个子元素,递归调用自身处理子对象,把返回的id数组合并到当前数组中 - 最终返回所有符合条件的id数组
方法二:简洁版(箭头函数 + flatMap)
如果你喜欢更简洁的代码,可以利用数组的flatMap方法自动扁平化递归返回的数组:
const data = { id: 240, name: 'FY1 2022', children: [ { id: 241, name: 'Q1 2022', children: [ { id: 242, name: 'Jan 2022', }, { id: 243, name: 'Feb 2022', }, { id: 244, name: 'Mar 2022', }, ], }, ], }; const extractLeafIds = obj => !('children' in obj) ? [obj.id] : obj.children.flatMap(child => extractLeafIds(child)); const result = extractLeafIds(data); console.log(result); // 输出: [242, 243, 244]
额外说明:
如果你的业务场景中,存在有children但为空数组的对象,且需要把这类对象的id也纳入结果,可以把判断条件调整为:
if (!obj.children || obj.children.length === 0) { // 收集id逻辑 }
内容的提问来源于stack exchange,提问作者stratdev
相关产品推荐
相关产品推荐

