活着
新人入坑,不定时分享一些工作中遇到的一些问题,或者觉得好的点

活着ccc

新人入坑,不定时分享一些工作中遇到的一些问题,或者觉得好的点

记录一次query 参数的转换问题

1. query 转 obj 

Object.fromEntries(new URLSearchParams(search))

2. obj 转 query

const queryParams = (data:any, isPrefix?:any) => {
  isPrefix = isPrefix ? isPrefix : false
    let prefix = isPrefix ? '?' : ''
    let _result = []
    for (let key in data) {
      let value = data[key]
      // 去掉为空的参数
      if (['', undefined, null].includes(value)) {
        continue
      }
      if (value.constructor === Array) {
        value.forEach(_value => {
          _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
        })
      } else {
        _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
      }
    }

    return _result.length ? prefix + _result.join('&') : ''
}

 queryParams(queryObj, history.location.pathname)

  

posted on 2022-01-24 16:09  活着ccc  阅读(162)  评论(0编辑  收藏  举报

导航