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

如何在JavaScript中从多维嵌套数组提取合并所有tags为单一标签列表

JavaScript提取嵌套tags数组实现方案

基础实现(仅用forEach)

// 初始化存储所有标签的空数组
const allTags = [];

fetch('你的API请求地址')
  .then(response => response.json())
  .then(fetchData => {
    // 遍历顶层profil数组
    fetchData.profil.forEach(profileItem => {
      // 遍历当前对象下的tags数组,逐个存入结果
      profileItem.tags.forEach(tag => {
        allTags.push(tag);
      });
    });
    // 此处可直接使用收集完成的allTags
    console.log('所有标签列表:', allTags);
  })

可选扩展:标签去重

如果需要过滤重复标签,可通过Set处理:

// 在收集完成后执行即可
const uniqueTags = [...new Set(allTags)];

实现逻辑

  • 无需手动指定数组索引,两次forEach会自动遍历所有层级的数组元素
  • 第一层遍历顶层profil数组拿到每个包含tags的对象
  • 第二层遍历每个对象的tags数组,将单个标签项追加到结果数组中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:57:02