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

从嵌套数组子属性创建新集合,提取唯一动物类型

获取嵌套数组中的唯一动物类型

嘿,我明白你现在卡在两层数组的映射操作上了,其实解决这个问题很简单,咱们用JavaScript的数组方法组合一下就能搞定!

假设你的数据已经存在一个变量data里,先看最简洁的实现方式:

const data = {
  "People" : [
    {
      "name": "Bob",
      "animals" : [
        { "name" : "Scott", "type" : "Cat" },
        { "name" : "Eva", "type" : "Cat" },
        { "name" : "Sven", "type" : "Dog" }
      ]
    },
    {
      "name": "Bob",
      "animals" : [
        { "name" : "Chris", "type" : "Dog" },
        { "name" : "Greg", "type" : "Cat" },
        { "name" : "Ior", "type" : "Horse" }
      ]
    }
  ]
};

// 核心代码
const uniqueAnimalTypes = [...new Set(
  data.People.flatMap(person => person.animals.map(animal => animal.type))
)];

console.log(uniqueAnimalTypes); // 输出: ["Cat", "Dog", "Horse"]

分步解释一下这个逻辑:

  • 扁平化数组:flatMap会先把每个人的animals数组映射出来,然后自动把这些子数组合并成一个大数组,直接解决了两层嵌套的问题。
  • 提取类型:接着用map从每个动物对象里取出type属性,得到一个包含所有类型(包括重复值)的数组。
  • 去重:用Set来过滤重复值,因为Set的特性就是只存储唯一元素,最后用扩展运算符[... ]把Set转成普通数组,就得到了咱们要的结果。

如果你的环境不支持flatMap(比如旧版浏览器),可以用这两种替代方案:

方案1:map + flat

const uniqueAnimalTypes = [...new Set(
  data.People.map(person => person.animals).flat().map(animal => animal.type)
)];

方案2:用reduce手动扁平化

// 先收集所有类型(含重复)
const allTypes = data.People.reduce((total, person) => {
  total.push(...person.animals.map(animal => animal.type));
  return total;
}, []);
// 再去重
const uniqueAnimalTypes = [...new Set(allTypes)];

这几种方法都能帮你得到所有唯一的动物类型,选最适合你项目环境的就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:36:37