/** * {} * @author yutent * @date 2023/08/10 10:07:51 */ const encode = encodeURIComponent const decode = decodeURIComponent export function noop() {} export function hideProp(host, name, value) { Object.defineProperty(host, name, { value, enumerable: false, writable: true }) } /** * query 序列化 */ function serialize(p, obj, callback) { var k if (Array.isArray(obj)) { obj.forEach(function (it, i) { k = p ? `${p}[${Array.isArray(it) ? i : ''}]` : i if (typeof it === 'object') { serialize(k, it, callback) } else { callback(k, it) } }) } else { for (let i in obj) { k = p ? `${p}[${i}]` : i if (typeof obj[i] === 'object') { serialize(k, obj[i], callback) } else { callback(k, obj[i]) } } } } /** * 将url query转回json对象 */ export function query2object(str = '') { let params = new URLSearchParams(str) let output = Object.create(null) for (let [_k, _v] of params.entries()) { let k = decode(_k) let v = decode(_v) let isArray = 0 if (/(\w+)\[(\w*?)\]/.test(k)) { let k1 = RegExp.$1 let k2 = RegExp.$2 k = k1 if (!k2 || +k2 === +k2) { v = [v] isArray |= 2 } else { isArray |= 1 v = { [k2]: v } } } if (output[k]) { if (isArray & 2) { output[k] = output[k].concat(v) } else if (isArray & 1) { Object.assign(output[k], v) } else { if (!Array.isArray(output[v])) { output[k] = [output[k]] } output[k].push(v) } } else { output[k] = v } } return output } /** * 将json数据转成 url query字符串 */ export function object2query(obj = {}) { if (obj === null) { return '' } if ( typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' ) { return obj } let output = [] let query = function (k, v) { output.push(k + '=' + encode(v)) } if (typeof obj === 'object') { serialize('', obj, query) } return output.join('&') }