如何从嵌套对象数组中提取唯一的features名称数组
提取嵌套数组中唯一的features名称列表
你的代码问题在于使用map会返回一个二维数组(每个元素对应原数组中每个对象的features名称子数组),且仅对每个子数组单独去重,无法实现全局去重并合并为一维数组的需求。
正确解法
可以通过先收集所有features名称到一维数组,再利用Set去重的方式实现:
方法1:使用flatMap简化合并与提取
const allFeatures = Array.from(new Set( property.flatMap(item => item.houses.features.map(feature => feature.name)) ));
方法2:使用reduce手动收集名称
// 先收集所有features名称到一维数组 const allFeatureNames = property.reduce((names, item) => { names.push(...item.houses.features.map(f => f.name)); return names; }, []); // 去重后得到结果 const allFeatures = [...new Set(allFeatureNames)];
结果验证
两种方法最终都会得到你预期的数组:
allFeatures = ['balcony', 'wifi', 'tiled floor', 'refrigerator', 'microwave']
内容的提问来源于stack exchange,提问作者japheth
相关产品推荐
相关产品推荐

