如何用JavaScript/Lodash提取两层数组嵌套对象中的car值?
问题分析与解决
首先,你大概率是混淆了「过滤外层数组对象」和「提取内层属性值」的逻辑,或是对嵌套结构的遍历判断写错了条件。先假设你的this.carLevels是常见的嵌套数组结构(类似下方示例),以此为基础分析:
this.carLevels = [ { level: "A", cars: [{ car: "Truck" }, { car: "Van" }] }, { level: "B", cars: [{ car: "Sedan" }, { car: "SUV" }] } ];
你可能犯的错误
用
_.filter/原生filter返回了外层对象而非car值
比如你可能写了类似这样的代码:// 错误:返回的是包含目标car的整个level对象,不是字符串"Truck"/"Sedan" const result = _.filter(this.carLevels, item => _.some(item.cars, { car: "Truck" }));这会返回
[{level: "A", cars: [...] }],并非你要的字符串数组。判断条件写错导致无结果
如果你的cars是对象数组,却直接用car === "Truck"判断,会因为对象和字符串类型不匹配导致some返回false,最终filter无结果:// 错误:cars里的元素是对象,不是字符串,判断条件不成立 const result = this.carLevels.filter(item => item.cars.some(car => car === "Truck"));
正确实现方法
需求1:提取所有car值(比如["Truck", "Van", "Sedan", "SUV"])
原生JS实现
// 用flatMap扁平化内层数组后提取属性 const allCars = this.carLevels.flatMap(level => level.cars.map(carItem => carItem.car)); // 兼容不支持flatMap的环境 const allCars = [].concat(...this.carLevels.map(level => level.cars.map(carItem => carItem.car)));
Lodash实现
const allCars = _.flatMap(this.carLevels, level => _.map(level.cars, 'car'));
需求2:只提取指定的car值(比如仅["Truck", "Sedan"])
原生JS实现
const targetCars = ["Truck", "Sedan"]; const result = this.carLevels .flatMap(level => level.cars.map(carItem => carItem.car)) .filter(car => targetCars.includes(car));
Lodash实现
const targetCars = ["Truck", "Sedan"]; const result = _.filter( _.flatMap(this.carLevels, level => _.map(level.cars, 'car')), car => _.includes(targetCars, car) );
如果你的carLevels结构和假设不同(比如嵌套更深),只需调整遍历层级即可——核心逻辑是先把嵌套的car属性全部提取到一维数组,再按需过滤。
内容的提问来源于stack exchange,提问作者Sunny
相关产品推荐
相关产品推荐

