xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-10-18 11:05  xgqfrms  阅读(108)  评论(2编辑  收藏  举报