JS工具函数

1.一维数组转tree结构

/**
 * 将一维数组转换为树形结构
  * @param {array} nodeList 原始数组
  * @param {string} parentKey 父标识符
  * @param {string} key 子标识符
  * @returns {array}
 */
 function arrayToTree(nodeList, parentKey, key) {
   if (!Array.isArray(nodeList)) return []
   const result = []
   const map = {}
   nodeList.forEach(item => { map[item[key]] = item })
   nodeList.forEach(item => {
     const parent = map[item[parentKey]]
     if (parent) {
       (parent.children || (parent.children = [])).push(item)
     } else {
       result.push(item)
     }
   })
   return result
 }

2.时间转换

/**
 * Parse the time to string
 * @param {(object | string | number)} time
 * @param {string} cFormat
 * @returns {string | null}
*/
function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support 1548221490638
        time = parseInt(time)
      } else {
        // support safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if ((typeof time === 'number') && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值