字节跳动前端一面算法题

511 阅读1分钟

输入:

const input = {
  'A': 1,
  'B.A': 2,
  'B.B': 4,
  'C.D.E': 3,
  'C.D.F': 5,
}

输出:

const output = {
    A: 1,
    B: {
      A: 2,
      B: 4,
    },
    C: {
      D: {
        E: 3,
        F: 5,
      },
    },
}

代码(Js)

const transform = (obj) => {
  const result = {};
  const toObjTree = (key, splitKey) => {
    let cur = result;
    splitKey.forEach((item, index) => {
      if (index === splitKey.length - 1) {
        cur[item] = obj[key];
      } else {
        cur[item] = cur[item] ? cur[item] : {};
      }
      cur = cur[item];
    })
  }
  Object.keys(obj).forEach(key => toObjTree(key, key.split('.')));
  return result;
}