Created
September 23, 2019 12:32
-
-
Save ArtemAvramenko/07e930ad94f97219e91be182cf2d2824 to your computer and use it in GitHub Desktop.
URLSearchParams to object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function objToParams(obj: any) { | |
let params = new URLSearchParams(); | |
for (let name in obj) { | |
let value = obj[name]; | |
if (Array.isArray(value)) { | |
for (let item of value) { | |
params.append(name, item); | |
} | |
} else { | |
params.set(name, value) | |
} | |
} | |
return params.toString(); | |
} | |
function paramsToObj<T>(paramsString: string, sample: T): T { | |
const parseScalar = (paramValue: string, sampleValue: any) => { | |
if (typeof sampleValue === 'boolean') { | |
paramValue = ('' + paramValue).toLowerCase().trim(); | |
return ['true', 'yes', '1'].indexOf(paramValue) >= 0; | |
} else if (typeof sampleValue === 'number') { | |
return Number(paramValue); | |
} | |
return paramValue; | |
} | |
let params = new URLSearchParams(paramsString); | |
let result = <any>{}; | |
for (let [name, value] of params) { | |
let sampleValue = (<any>sample)[name]; | |
if (Array.isArray(sampleValue)) { | |
let array = result[name] || []; | |
array.push(parseScalar(value, sampleValue[0])) | |
result[name] = array; | |
} else { | |
result[name] = parseScalar(value, sampleValue); | |
} | |
} | |
return result; | |
} | |
let params = objToParams({ | |
description: 'xxx', | |
tags: ['a', 'b'], | |
isStarted: true | |
}); | |
console.log(params); | |
let result = paramsToObj(params, { | |
tags: [0], | |
isStarted: true | |
}); | |
console.log(JSON.stringify(result)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment