实现 qs.stringify 和 qs.parse 方法
栏目:
Javascript
发布时间:2021-12-24
/**
* 目前支持 2 个方法,需要再扩展
*/
export const stringify = (obj = {}) => {
const isNullOrUndefined = val => {
return [null, undefined].includes(val)
}
Object.keys(obj).forEach(key => {
if (isNullOrUndefined(obj[key])) {
delete obj[key]
}
})
return Object.keys(obj).map(key => {
const val = obj[key]
if (val instanceof Array) {
if (val.length) {
return val.map((v, index) => {
return [`${key}[${index}]`, v].join('=')
}).join('&')
} else {
return ''
}
}
return [encodeURIComponent(key), encodeURIComponent(obj[key])].join('=')
}).filter(val => val.length).join('&')
}
export const parse = (str = '') => {
const obj = {}
str.split('&').forEach(itemStr => {
const itemArr = itemStr.split('=')
obj[decodeURIComponent(itemArr[0])] = decodeURIComponent(itemArr[1])
})
return obj
}
export default {
stringify,
parse
}
本文地址:https://www.tides.cn/p_js-qs