JavaScript 中的 flatMap 是什么?它如何让我的代码更简洁?

2025-06-08

JavaScript 中的 flatMap 是什么?它如何让我的代码更简洁?

您是否曾经查看过 JavaScript 内置函数并对自己说:

我知道这是什么,但我不知道在哪里可以用它。

嗯,当我读到这篇文章时,这个想法就浮现在我的脑海里Array.flatMap()。于是我开始在日常编程中寻找它的应用,然后,哇!我找到了一个用例。在这篇文章中,我们将首先了解什么Array.flatmap()是 ,然后看看我是如何在一个实际问题中使用它的。

到底是什么Array.flatMap

FlatMap 是两个词的混合,这两个词源自拉丁词 blah blah blah...

只是在开玩笑。

Array.flatMap是两种数组方法的混合Array.flatArray.map单独来看,

  • Array.flat用于展平嵌套数组。例如
const names = ['Amit', 'Karishma', 'Kunal', ['Pankaj', 'Rahee']];

console.log(names.flat());
// expected output: ["Amit", "Karishma", "Kunal", "Pankaj", "Rahee"]
Enter fullscreen mode Exit fullscreen mode
  • Array.map用于通过对每个数组元素执行操作并返回一个值来创建新数组。例如
const names = ['Amit', 'Karishma', 'Kunal', 'Pankaj', 'Rahee'];
const everyOneLovesDogs = names.map((name) => {
  return `${name} loves dogs`;
});

console.log(everyOneLovesDogs);
// expected output: ["Amit loves dogs", "Karishma loves dogs", "Kunal loves dogs", "Pankaj loves dogs", "Rahee loves dogs"]
Enter fullscreen mode Exit fullscreen mode

正如你所猜测的,Array.flatMapflatMap 会映射一个数组,然后将返回数组中的嵌套数组展平。flatMap 的一个简单示例如下:

const usersWithInterests = [
  {
    name: 'Amit',
    interests: ['Cricket', 'Music'],
  },
  {
    name: 'Karishma',
    interests: ['Drawing', 'Reading'],
  },
  {
    name: 'Pranav',
    interests: ['Crafting', 'Biking'],
  }
];

const interests = usersWithInterests.flatMap((user) => {
  return user.interests;
});

console.log(interests);
// Expected Output: ["Cricket", "Music", "Drawing", "Reading", "Crafting", "Biking"]
Enter fullscreen mode Exit fullscreen mode

我如何Array.flatMap在实际问题中使用它?

我正在开发一个功能,需要创建一个产品类别的下拉菜单。API 的实际响应getProducts如下所示:

const response = {
  "status": "success",
  "products": [
    {
      "name": 'One Plus 7T',
      "categories": ['Technology', 'Mobile', 'SmartPhone'],
      "description": 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      "rating": '4.5'
    },
    {
      "name": 'MacBook Pro 2018',
      "categories": ['Technology', 'Computer', 'Laptop'],
      "description": 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      "rating": '4.8'
    },
    {
      "name": 'LG Monitor 221G',
      "categories": ['Technology', 'Monitor'],
      "description": 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      "rating": '4.3'
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

产品对象以类别作为键,其值存储在数组中。

所以我必须做三件事

  • 获取每个产品的类别
  • 展平该数组
  • 从数组中获取唯一值。

前两个任务中我没有使用两个单独的函数,而是使用了一个函数:Array.flatmap。然后对该数组应用设置操作来获取唯一值。

最终的代码片段如下所示:

const { products } = response;
const allCategories = products.flatMap((product) => {
  return product.categories;
});

const uniqueCategories = [...new Set(allCategories)];

console.log(uniqueCategories);
// Expected Output: ["Technology", "Mobile", "SmartPhone", "Computer", "Laptop", "Monitor"]
Enter fullscreen mode Exit fullscreen mode

结论

我希望现在大家也能Array.flatMap在合适的情况下运用这些技巧,写出更简洁的代码。更多类似的趣闻轶事,敬请期待。祝大家编码愉快!

本文最初发表于此处。想了解更多精彩内容,请访问我的博客

鏂囩珷鏉ユ簮锛�https://dev.to/amitkhonde/what-is-flatmap-in-javascript-and-how-made-my-code-cleaner-3nbn
PREV
软件项目名称的由来 JavaScript(编程语言) MySQL(数据库管理系统) Git(版本控制系统) Ubuntu(操作系统) Java(编程语言) Python(编程语言) Ruby(编程语言) Scala(编程语言) Django(Python 框架) Chrome(浏览器) Mozilla(公司) Firefox(浏览器) Laravel(PHP 框架) Hadoop(开源大数据软件) Skype(即时通讯应用程序) Adob​​e(公司) Apache(软件基金会) Microsoft(公司) Zend Technologies(组织) Xerox(公司)
NEXT
JavaScript 速记技巧