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

如何在JavaScript中从现有对象数组提取不重复的tag值数组

解决方案与实现思路

假设你的数组结构类似这样(每个对象包含tags数组属性):

const data = [
  { id: 1, title: '文章1', tags: ['前端', 'JavaScript'] },
  { id: 2, title: '文章2', tags: ['CSS', '前端'] },
  { id: 3, title: '文章3', tags: ['JavaScript', 'React'] },
  { id: 4, title: '文章4', tags: ['Vue'] }
];

快速实现代码

一行代码就能完成提取+去重:

const uniqueTags = [...new Set(data.flatMap(item => item.tags || []))];

分步拆解思路

  1. 提取所有tag
    用flatMap遍历数组中的每个对象,取出tags属性。如果有的对象没有tags或者tags为null/undefined,用|| []兜底避免报错。flatMap会自动把嵌套的tags数组拍平成一维数组。

  2. 去重处理
    ES6的Set结构会自动过滤重复值,把提取到的所有tag传入Set后,再用扩展运算符...转成数组,就得到了不重复的tag列表。

兼容旧环境的替代方案

如果项目需要兼容不支持flatMap和Set的旧浏览器,可以用以下写法:

// 提取所有tag
const allTags = [];
data.forEach(item => {
  if (item.tags && Array.isArray(item.tags)) {
    allTags.push(...item.tags);
  }
});

// 去重
const uniqueTags = allTags.filter((tag, index) => allTags.indexOf(tag) === index);

特殊情况处理

如果你的tags是单个字符串(不是数组),只需要把flatMap改成map即可:

const uniqueTags = [...new Set(data.map(item => item.tag || ''))].filter(tag => tag);

内容的提问来源于stack exchange,提问作者Yaakoubi Mohammed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:50:29