- When processing data, it is often necessary to filter and traverse the data in order to convert the data into a format that meets our requirements, such as the following scenarios:
Filter out data with empty names, if the age is less than 18, set disabled: true
, if it is greater than or equal to 18, set disabled: false
// 原始数据
[{name: '小明', age: 15}, {name: '张三', age: 18}, {name: '李四', age: 20}, {name: '', age: 30}]
// 转换后数据
[{name: '小明', age: 15, disabled: true}, {name: '张三', age: 18, disabled: false}, {name: '李四', age: 20, disabled: false}]
- For most developers, the first method that comes to mind should be filter and map.
[{name: '小明', age: 15}, {name: '张三', age: 18}, {name: '李四', age: 20}, {name: '', age: 30}].filter(item => item.name).map(item => ({...item, disabled: item.age >= 18 ? false : true}))
Although this method needs to be traversed twice, I personally think it is quite simple. Can it be solved by traversing once? Obviously yes, use Array.flatMap()
[{name: '小明', age: 15}, {name: '张三', age: 18}, {name: '李四', age: 20}, {name: '', age: 30}].flatMap(item => item.name ? [{...item, disabled: item.age >= 18 ? false : true}] : [])
flatMap
is more like a combination of map and filter, but flatMap is more powerful, it allows us to manipulate each item in the array in a more subtle way, such as:
const arr = [1,3].flatMap(number => {
return [number, 2 * number, 3 * number];
})
// [1, 2, 3, 3, 6, 9]
The way flatMap
works is simple, it flattens each item in the array once, so the example returns the equivalent of [...[1,2,3], ...[3,6,9]]
. If you want to flatten a two-dimensional array, you can use [[2,3],4].flatMap(item => item)
directly. Of course, the easiest way to flatten the array is to use [[2,3],4].flat(Infinity)
.
How handles array mapping efficiently was first published on on , if it helps you, don't forget to like and support it🎉
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。