Skip to content

Instantly share code, notes, and snippets.

@deadmann
Created July 3, 2021 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deadmann/42b420d20867ed9a822c499fd0f8f5ff to your computer and use it in GitHub Desktop.
Save deadmann/42b420d20867ed9a822c499fd0f8f5ff to your computer and use it in GitHub Desktop.
Serialize and Flatting object data into string
const findObjectDataRecursive = function (obj, subKey='') {
let dataArray = [];
if (typeof (obj) === "undefined" || obj === null)
return undefined;
if (typeof obj === "object"){
let result = [];
if (Array.isArray(obj)){
for(let i = 0; i < obj.length; i++) {
let x = findObjectDataRecursive(obj[i], subKey + '['+i+']');
if (typeof x !== "undefined"){
for (const e of x) {
result.push(e);
}
}
}
} else {
for (const objKey in obj) {
if (obj.hasOwnProperty(objKey)){
let key = subKey!=null && subKey!==""? subKey + '['+objKey+']' : objKey;
let x = findObjectDataRecursive(obj[objKey], key);
if (typeof x !== "undefined"){
for (const e of x) {
result.push(e);
}
}
}
}
}
for (const resultKey of result) {
dataArray.push(resultKey);
}
}
else{
dataArray.push(subKey + '=' + encodeURIComponent(obj));
}
return dataArray;
};
const serialize = function (obj) {
let data = findObjectDataRecursive(obj);
let str = "";
let i = 0;
do {
str += data[i++];
} while(i<data.length && (str+="&"));
return str;
}
const filterUrl = serialize(filters);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment