1. // 方案 1
  2. function recursionFlat(ary = []) {
  3. const res = []
  4. ary.forEach(item => {
  5. if (Array.isArray(item)) {
  6. res.push(...recursionFlat(item))
  7. } else {
  8. res.push(item)
  9. }
  10. })
  11. return res
  12. }
  13. // 方案 2
  14. function reduceFlat(ary = []) {
  15. return ary.reduce((res, item) => res.concat(Array.isArray(item) ? reduceFlat(item) : item), [])
  16. }
  17. // 测试
  18. const source = [1, 2, [3, 4, [5, 6]], '7']
  19. console.log(recursionFlat(source))
  20. console.log(reduceFlat(source))

Object Flat

  1. function objectFlat(obj = {}) {
  2. const res = {}
  3. function flat(item, preKey = '') {
  4. Object.entries(item).forEach(([key, val]) => {
  5. const newKey = preKey ? `${preKey}.${key}` : key
  6. if (val && typeof val === 'object') {
  7. flat(val, newKey)
  8. } else {
  9. res[newKey] = val
  10. }
  11. })
  12. }
  13. flat(obj)
  14. return res
  15. }
  16. // 测试
  17. const source = { a: { b: { c: 1, d: 2 }, e: 3 }, f: { g: 2 } }
  18. console.log(objectFlat(source));

Flat化数组或者对象主要用于把复杂的结构梳理出来,有一个很重要的实践就是对应的react的菜单的效果的实践效果的实践