convert URL Query String to Object All In One
convert URL Query String to Object All In One
URL / query string / paramas
query string to object
let str = "name=xgqfrms&sex=男&age=18&";
const params = new URLSearchParams(str);
for (let p of params) {
console.log(p);
}
["name", "xgqfrms"]
["sex", "男"]
["age", "18"]
filter
let str = "name=xgqfrms&sex=男&age=18&";
str = str.split(`&`).filter(item => item.length).join(`&`);
// "name=xgqfrms&sex=男&age=18"
str.split(`&`).filter(item => item.length).reduce((acc, item) => {
const [key, value] = [...item.split(`=`)];
acc[key] = value;
}, {})
reduce
let str = "name=xgqfrms&sex=男&age=18&";
str = str.split(`&`).reduce((acc, item) => acc += item.length ? item : "", "");
// "name=xgqfrmssex=男age=18"
demo
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-01
* @modified
*
* @description string to object
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
const str = "name=xgqfrms&sex=男&age=18&";
const obj = str.split(`&`).filter(item => item.length).reduce((acc, item) => {
const [key, value] = [...item.split(`=`)];
acc[key] = value;
return acc;
}, {})
log(`obj =`, obj);
// obj = { name: 'xgqfrms', sex: '男', age: '18' }
refs
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13833196.html
未经授权禁止转载,违者必究!