JS数组中的方法 flat(),flatMap()
一、flat()
官方解释:该方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。 口水话解释:数组降维操作
语法
var newArray = arr.flat([depth])
参数:
depth 可选 指定要提取嵌套数组的结构深度(降维深度),默认值为 1。
例子
1.扁平化嵌套数组
const newArr = [1, 2, 3, [a, b, c, [Aa]]].flat(2)//[1,2,3,"a","b","c","Aa] const newArr2 = [1, 2, 3, [a, b, c, [Aa]]].flat(2)//[1, 2, 3, [a, b, c, [Aa]]].flat(1)
2.Infinity扁平化任意深度
const newArr2 = [1, 2, 3, [a, b, c, [Aa]]].flat(Infinity)//[1, 2, 3, [a, b, c, [Aa]]].flat(1)
3.扁平化与空项
const newArr = [1, 2, 3, , 6, 8].flat() // [1, 2, 3, 6, 8]
二、flatMap()
官方解释:flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。 口水话:xxx
语法
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) { // 返回新数组的元素 }[, thisArg])
参数
callback
可以生成一个新数组中的元素的函数,可以传入三个参数:
currentValue
当前正在数组中处理的元素
index可选
可选的。数组中正在处理的当前元素的索引。
array可选
可选的。被调用的 map 数组
thisArg可选
可选的。执行 callback 函数时 使用的this 值。 返回值 一个新的数组,其中每个元素都是回调函数的结果,并且结构深度 depth 值为1。
描述
有关回调函数的详细描述,请参见 Array.prototype.map() 。 flatMap 方法与 map 方法和深度depth为1的 flat 几乎相同.
示例
Map 与 flatMap const arr1 = [1, 2, 3, 4] const arr2 = arr1.map(x => [x * 2]) // [[2], [4], [6], [8]]
const arr3 = arr1.flatMap(x => [x * 2]) // [2, 4, 6, 8]
// 只会将 flatMap 中的函数返回的数组 “压平” 一层 const arr4=arr1.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]]
扁平化实际运用
const data = [ { code: 1001, name: zs, age: 12, address: 重庆, mark: , sourceCodeList: [ { checked: false, num: 0, mark: 主导打包 }, { checked: true, num: 1, mark: 333 } ] }, { code: 1002, name: ls, age: 15, address: 武汉, sourceCodeList: [ { checked: false, num: null, mark: 1111 }, { checked: true, num: 1, mark: 111 } ] }, { code: 1003, name: ww, age: 15, address: 深圳, sourceCodeList: [{ checked: false, num: 11, mark: }] } ] const stockRegisterDetailList2 = data.flatMap( ({ sourceCodeList, ...parent }) => sourceCodeList.map(child => ({ ...parent, ...child })) ) const stockRegisterDetailList3 = data .map(({ sourceCodeList, ...parent }) => sourceCodeList.map(child => ({ ...parent, ...child })) ) .flat() console.log(stockRegisterDetailList2) console.log(stockRegisterDetailList3)
下一篇:
集成 nacos注册中心配置使用