Code transformation

14.09.20201 Min Read — In Algorithms

target

const entry = {
  'a.b.c.dd': 'abcdd',
  'a.d.xx': 'adxx',
  'a.e': 'ae'
}

// 要求转换成如下对象
const output = {
  a: {
    b: {
      c: {
        dd: 'abcdd'
      }
    },
    d: {
      xx: 'adxx'
    },
    e: 'ae'
  }
}

answer

const transform = (input: { [P in string]: string }): Object => {
  const ret = {}
  Object.entries(input).forEach(([keys, val]) => {
    let root = ret
    keys.split('.').forEach((key, ind, arr) => {
      if (ind === arr.length - 1) root[key] = val
      else {
        root[key] = root[key] || {}
        root = root[key]
      }
    })
  })
  return ret
}
你必须登录才能发表评论