typescript 深层次对象内层(N)转外层(N),支持多层级递归转换,多应用于多语言数据结构转换

如下数据结构转换

var a = {
  b: {
    en: 1,
    zh: 2,
  },
  c: {
    en: 3,
    zh: 4,
  },
}
//===>
var b = {
  en: {
    b: 1,
    c: 3,
  },
  zh: {
    b: 2,
    c: 4,
  },
}

Usage


let source: Record<string, any> = {
  languages: {
    zh: '简体中文',
    en: 'English',
  },
  nav: {
    home: {
      zh: '',
      en: 'home',
    },
    think: {
      zh: '',
      en: 'think',
    },
    code: {
      zh: '',
      en: 'code',
    },
    project: {
      zh: '',
      en: 'project',
    },
    vlog: {
      zh: '',
      en: 'vlog',
    },
    about: {
      zh: '',
      en: 'about',
    },
  },
  text: {
    origin: {
      original: {
        zh: '原创',
        en: 'og',
      },
      reprint: {
        zh: '转载',
        en: 'rp',
      },
      hybrid: {
        zh: ' 混撰',
        en: 'hb',
      },
    },
    slogan: {
      zh: '砥砺前行,未来可期',
      en: 'Because the mountain was there.',
    },
    category: {
      name: {
        zh: '分门别类',
        en: 'Categories',
      },
      empty: {
        zh: '未分类',
        en: 'no cate',
      },
    },
    search: {
      zh: '向外探索,向内觉知',
      en: 'Search...',
    },
  },
}
let resObj: Record<string, any> = {
  en: {},
  // zh: {},
}
function judge(
  res: Record<string, any>,
  obj: Record<string, any>,
  type: string
) {
  for (const k in obj) {
    let v = obj[k]
    if (typeof v !== 'string' && !v[type]) {
      res[k] = {}
      judge(res[k], v, type)
    } else {
      res[k] = v[type]
    }
  }
}
function formatData(obj: Record<string, any>) {
  Object.keys(resObj).forEach(v => {
    judge(resObj[v], obj, v)
  })
}
formatData(source)
export default resObj
posted @ 2019-11-25 10:34  霜末之冬  阅读(778)  评论(0编辑  收藏  举报