You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从嵌套对象数组中提取唯一的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:50:26