常用JS工具函数(深拷贝、数组转树等等)

  // 深拷贝
  function deepClone(arr) {
    if (arr && typeof arr === 'object') {
      const target = arr.constructor === Array ? [] : {}
      Object.keys(arr).forEach(key => {
        if (arr[key] && typeof arr[key] === 'object') {
          target[key] = deepClone(arr[key])
        } else {
          target[key] = arr[key]
        }
      })
      return target
    } else {
      throw new Error('参数不是对象或数组')
    }

  }
  // 数组扁平化
  function flatArray(arr, newArr = []) {
    arr.forEach(item => {
      if (item.constructor === Array) {
        flatArray(item, newArr)
      } else {
        newArr.push(item)
      }
    })
    return newArr
  }
  // 数组转树
  function listToTree(arr, id = 'id', pId = 'pId', children = 'children') {
    const cloneData = deepClone(arr)
    return cloneData.filter(father => {
      let branchData = cloneData.filter(child => father[id] === child[pId])
      branchData.length > 0 ? father[children] = branchData : ''
      return father[pId] === 0
    })
  }
  let arr = [
    {id: 1, pId: 0, name: '1'},
    {id: 2, pId: 1, name: '1-1'},
    {id: 3, pId: 2, name: '1-1-1'},
    {id: 4, pId: 3, name: '1-1-1-1'}
  ]
  // console.log('listToTree(arr):', listToTree(arr))
  // 数组转树2
  function arrToTreeNew(arr) {
    const result = []
    const map = {}
    arr.forEach(item => {
      map[item.id] = item
    })
    arr.forEach(item => {
      const parent = map[item.pid]
      if (parent) {
        (parent.children || (parent.children = [])).push(item)
      } else {
        result.push(item)
      }
    })
    return result
  }
  const arr2 = [
    {id: 1, pid: 0, name: 'body'},
    {id: 2, pid: 1, name: 'title'},
    {id: 3, pid: 1, name: 'div'},
    {id: 4, pid: 3, name: 'span'},
    {id: 5, pid: 3, name: 'icon '},
    {id: 6, pid: 4, name: 'subspan'}
  ]
  // console.log(arrToTreeNew(arr2))
// url参数转对象
function getQueryObject(url) {
	// 没有传url,拿地址栏的url
    url = url || window.location.search
    const search = url.substring(url.lastIndexOf('?') + 1)
    const obj = {}
    const reg = /([^?&=]+)=([^?&=]*)/g
    search.replace(reg, (rs, $1, $2) => {
      const name = decodeURIComponent($1)
      let val = decodeURIComponent($2)
      val = String(val)
      obj[name] = val
      return rs
    })
    return obj
  }
	// params对象类型为对象
  function isObject(params) {
    return Object.prototype.toString.call(params) === '[object Object]'
  }
  // params对象类型为数组
  function isArray(params) {
    return Object.prototype.toString.call(params) === '[object Array]'
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值