如何遍历嵌套Car对象,提取所有SUV类型的carURL数组?
提取嵌套Car对象中所有SUV的carUrl数组
类型定义与示例数据
首先是定义的TypeScript类型:
export type CarId = string; export type CarType = 'sedan' | 'suv' | 'wagon'; export type Car = { id: CarId; type: CarType; options?: Record<string, string | number | boolean | string[] | null>; models?: Car[]; }
多层嵌套的Car对象示例:
export const cars: Car = { type: 'sedan', id: 'a', options: {}, models: [ { type:'sedan', id: 'b', options: {}, models: [] }, { type:'wagon', id: 'c', options: {}, models: [ { type:'wagon', id: 'd', options: {}, models: [ { type:'suv', id: 'e', options: { carUrl: 'https://audi.com/a4' }, models: [] } ] } ] }, ] }
问题分析
需要实现一个函数,提取所有type为suv的Car实例中options.carUrl的值,组成扁平数组。你尝试的代码存在以下问题:
- 遍历逻辑错误,错误地将对象属性值与属性名做比较
- 未递归处理嵌套的
models数组 - 未正确判断
options中是否存在有效的carUrl
正确实现
采用递归遍历的方式,处理当前Car及其所有子models:
export function extractSuvCarUrls(car: Car): string[] { let urls: string[] = []; // 检查当前车辆是否是SUV,且存在有效的carUrl if (car.type === 'suv' && car.options?.carUrl && typeof car.options.carUrl === 'string') { urls.push(car.options.carUrl); } // 递归处理子models数组 if (car.models?.length) { car.models.forEach(childCar => { urls = urls.concat(extractSuvCarUrls(childCar)); }); } return urls; }
调用示例
const result = extractSuvCarUrls(cars); console.log(result); // 输出: ['https://audi.com/a4']
说明
- 递归遍历每个Car节点,先检查当前节点是否符合条件,再处理其子节点
- 加入类型判断确保提取的是有效的字符串URL
- 使用
concat合并递归返回的数组,最终得到扁平的URL数组
内容的提问来源于stack exchange,提问作者JP. K.
相关产品推荐
相关产品推荐

