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

如何从Formdata数组中提取所有sites对象的name属性值

实现方案

你可以通过两次遍历结合数组扁平化的方式提取所有name值,推荐使用flatMap直接完成遍历+扁平化操作,代码如下:

const Formdata = [{
    "id": "6efcf3f7-5d29-4a88-8ce9-346229a86765",
    "title": "Deepak test form 2",
    "version": "1",
    "sites": [{
      "id": "d7f2b290-2820-401a-a347-9a4dd05ec02b",
      "name": "TEST-TRIAL-001120"
    }],
    "status": "Not Linked"
  },
  {
    "id": "89e5a12d-913d-4f5d-a030-b172af9e27f0",
    "title": "Deepak Test form 1",
    "version": "1",
    "sites": [],
    "status": "Not Linked"
  },
  {
    "id": "79a15768-762e-4ff8-b565-31274a38b22d",
    "title": "1.7 Form",
    "version": "1",
    "sites": [{
      "id": "32369d1d-f247-4a75-8c14-490c8393dbb8",
      "name": "Mubashir Test Site - 001001"
    }, {
      "id": "d7f2b290-2820-401a-a347-9a4dd05ec02b",
      "name": "TEST-TRIAL-001120"
    }, {
      "id": "a6526163-3ed7-4125-8f32-e0066fc6fe24",
      "name": "TEST SITE -001"
    }],
    "status": "Not Linked"
  }
]

// 核心实现代码
const siteNames = Formdata.flatMap(form => {
  // 遍历当前form的sites数组,提取所有name
  return form.sites.map(site => site.name)
})

console.log(siteNames)

运行输出

["TEST-TRIAL-001120", "Mubashir Test Site - 001001", "TEST-TRIAL-001120", "TEST SITE -001"]

兼容写法(不支持flatMap的场景)

如果运行环境不支持flatMap,可以拆分写成map+flat的组合:

const siteNames = Formdata.map(form => form.sites.map(site => site.name)).flat()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:30:04