Created
February 1, 2021 17:13
-
-
Save paulinep/1bb188d55dfb779ac3014b7cf1da2776 to your computer and use it in GitHub Desktop.
функции для взаимной конвертации (туда обратно) Из JSON в строку location.search
This file contains 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
/*превращает объект в строку вида | |
criteria%5Bproperties%5D%5Bx0005656%5D%5Bfrom%5D=1&criteria%5Bproperties%5D%5Bx0005656%5D%5Bto%5D=4&sorting%5Bstock%3A545%5D=asc | |
*/ | |
export function serialize (obj: ICatalogParams, prefix=''): string { | |
var str = [] | |
let p: keyof ICatalogParams; | |
for (p in obj) { | |
if (obj.hasOwnProperty(p)) { | |
var k = prefix ? prefix + "[" + p + "]" : p, | |
v = obj[p]; | |
str.push((v !== null && typeof v === "object") ? | |
serialize(v, k) : | |
encodeURIComponent(k) + "=" + encodeURIComponent(v as string | number | boolean)); | |
} | |
} | |
return str.join("&"); | |
} | |
/*обратно в объект произвольной вложенности с помощью функции вкладывающей объекты по массиву строковых путей */ | |
export function deserialize(keys: string[], values: (string | string[] | null)[]): ICatalogParams { | |
let params: any= {} | |
keys.map((key, index)=>{ | |
if(key.indexOf('[') > -1){ | |
let param = key.split('[', ) | |
if(param && param.length) { | |
let newParam= param.map(item => { | |
return item.replace(']', '')//Не берем первую закрывающую ] здесь формируется путь до вложенного объекта | |
}) | |
if(param.length > 2){ | |
assign(params, newParam, values[index]) | |
}else{ | |
params={...params, [newParam[0]]: {...params[newParam[0]], [newParam[1]] : values[index]} } | |
} | |
} | |
}else{ | |
params= {...params, [key]: values[index]} | |
} | |
}) | |
return params | |
} | |
function assign(obj: any, keyPath: string[], value: string | string[] | null) { | |
const lastKeyIndex = keyPath.length-1; | |
for (let i = 0; i < lastKeyIndex; ++ i) { | |
const key = keyPath[i]; | |
if (!(key in obj)){ | |
obj[key] = {} | |
} | |
obj = obj[key]; | |
} | |
obj[keyPath[lastKeyIndex]] = value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment