对象扁平化

59 阅读1分钟

对象扁平化是面试中比较常考的题,特此记录下

题目:

const entryObj = {
  a: {
    b: {
      c: {
        d: 'abcd',
      },
    },
    e: [
      {
        age: '18',
      },
      {
        name: 'lzw',
      },
    ],
    f: 'ff',
  },
  g: 'gg',
}
需要转换成
const entryObj = {
  'a.b.c.d': 'abcd',
  'a.f': 'ff',
  'a[e].0.age': '18',
  'a[e].1.name': 'lzw',
  'g': 'gg',
}

image.png 代码实现:

const handler = cusObj => {
  let newObj = {}
  const flat = (obj, path) => {
    for (let k in obj) {
      if (typeof obj[k] === 'object' && obj[k] !== null) {
        if (!path) {
          flat(obj[k], k)
        } else if (Array.isArray(obj[k])) {
          flat(obj[k], `${path}[${k}]`)
        } else {
          flat(obj[k], `${path}.${k}`)
        }
      } else {
        if (!path) {
          newObj[k] = obj[k]
        } else {
          newObj[`${path}.${k}`] = obj[k]
        }
      }
    }
  }
  flat(cusObj, '')
  return newObj
}

思路里也提到了需要判断 path 是否为空的情况,第 6 行和第 14 行的逻辑正是为了避免以下情况:

image.png