ES6中flat(),flatMap()使用方法

文章介绍了如何使用JavaScript中的flatMap方法替代filter和map的组合,以简化处理嵌套数组并设置颜色逻辑。flat方法用于将多层嵌套数组转换为一维,而flatMap结合了映射和扁平化功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实际应用:

1.代替filter+map的连用

例:现有一组数据,只展示days>=30的数据,且work为1设置color:“#ffffff”,work:0设置color:“#ff0000”:

const dataList = [{
    days: 31,
    name: "占位文字31",
    work: 0
}, {
    days: 30,
    name: "占位文字30",
    work: 1
}, {
    days: 29,
    name: "占位文字29",
    work: 1
}, {
    days: 28,
    name: "占位文字28",
    work: 0
}, {
    days: 27,
    name: "占位文字27",
    work: 1
}];
const newdataList = dataList.flatMap(item => {
    if (item.days <= 30) {
        const color = item.work == 1 ? "#ffffff" : "#ff0000"
        item.color = color;
        return [item];
    } else {
        return [];
    }
})
console.log(newdataList)
// [
//     {"days": 30,"name": "占位文字30","work": 1,"color": "#ffffff"},
//     {"days": 29,"name": "占位文字29","work": 1,"color": "#ffffff"},
//     {"days": 28,"name": "占位文字28","work": 0,"color": "#ff0000"},
//     {"days": 27,"name": "占位文字27","work": 1,"color": "#ffffff"}
// ]

2.通过递归将树形数据转换为扁平数组

const routes = [
  {
    path: '/home',
    children: [
      {
        path: 'dashboard',
        children: [
          { path: 'overview' },
          { path: 'settings' }
        ]
      },
      { path: 'profile' }
    ]
  },
  {
    path: '/about',
    children: [
      { path: 'team' },
      { path: 'contact' }
    ]
  }
];
//获取扁平数据
const flatMapRecursive = (list) => {
  return list.flatMap(item => {
    const {children, ...currentItem} = item;
    return children ? [currentItem, ...flatMapRecursive(children)] : [currentItem]
  })
}
//扁平数据
const flatRouters = flatMapRecursive(routes)
console.log(flatRouters)

基础知识:

数组的成员有时还是数组,Array.prototype.flat()用于将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组,对原数据没有影响。

[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]

flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数,默认为1。

[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]

如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数

[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]

flatMap()方法对原数组的每个成员执行一个函数(相当于执行Array.prototype.map()),然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。

// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]

flatMap()只能展开一层数组。

// 相当于 [[[2]], [[4]], [[6]], [[8]]].flat()
[1, 2, 3, 4].flatMap(x => [[x * 2]])
// [[2], [4], [6], [8]]

flatMap()方法的参数是一个遍历函数,该函数可以接受三个参数,分别是当前数组成员、当前数组成员的位置(从零开始)、原数组。

arr.flatMap(function callback(currentValue[, index[, array]]) {
  // ...
}[, thisArg])

flatMap()方法还可以有第二个参数,用来绑定遍历函数里面的this。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值