array : flatMap vs map

23 阅读1分钟

数据转换示例

原始数据结构:

positions: [
  {
    id: "pos1",
    rects: [
      { x: 100, y: 200, w: 50, h: 30 },
      { x: 150, y: 250, w: 60, h: 40 }
    ]
  },
  {
    id: "pos2", 
    rects: [
      { x: 300, y: 400, w: 70, h: 50 }
    ]
  }
]

转换后的结果:

[
  { 
    x: 100, y: 200, w: 50, h: 30, 
    position: { id: "pos1", rects: [...] } 
  },
  { 
    x: 150, y: 250, w: 60, h: 40, 
    position: { id: "pos1", rects: [...] } 
  },
  { 
    x: 300, y: 400, w: 70, h: 50, 
    position: { id: "pos2", rects: [...] } 
  }
]

为什么用 flatMap 而不是 map

如果用 map ,结果会是嵌套数组:

// 用 map 的结果
[
  [rect1, rect2],  // position1 的 rects
  [rect3]          // position2 的 rects  
]

// 用 flatMap 的结果
[rect1, rect2, rect3]  // 扁平化的数组

安全性处理

代码中的 ?. 和 || [] 是为了处理可能的 null/undefined 值:

  • paperSheet?.positions?.flatMap(...) - 如果 paperSheet 或 positions 为空,返回 undefined
  • || [] - 如果前面返回 undefined,则返回空数组
  • position.rects?.flatMap(...) || [] - 如果某个 position 的 rects 为空,返回空数组 这样确保了即使数据不完整,函数也能安全运行并返回一个有效的数组。