Created
July 3, 2021 13:55
-
-
Save deadmann/42b420d20867ed9a822c499fd0f8f5ff to your computer and use it in GitHub Desktop.
Serialize and Flatting object data into string
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
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