js 處理請求query 函式記錄
阿新 • • 發佈:2019-01-07
export function stringify(obj = {}) {
return Object.keys(obj)
.filter(k => obj[k] || +obj[k] === 0)
.map((k) => {
let value = obj[k];
if (typeof value == 'object') {
value = encodeURIComponent(JSON.stringify(value));
} else {
value = encodeURIComponent (value);
}
return `${encodeURIComponent(k)}=${value}`;
})
.join('&');
}
export function parse(str) {
const obj = {};
str.split('&').forEach((item) => {
const array = item.split('=');
obj[array[0]] = decodeURIComponent(array[1]);
});
return obj;
}
export default {
stringify,
parse,
};