Necesitaba convertir un objeto en parámetros de consulta.
He usado el código sugerido aquí para la función recursiva.
const serializeObject = (obj, label) => { const pairs = []; for (const prop in obj) { if (!obj.hasOwnProperty(prop)) { continue; } if (typeof obj[prop] === 'object') { pairs.push(serializeObject(obj[prop]), prop); continue; } if (label !== undefined) { pairs.push( "pageSearch[" + label + "][" + prop + "]" + "=" + obj[prop] ); } else { pairs.push("pageSearch[" + prop + "]" + "=" + obj[prop]); } } return pairs.join("&"); }; He agregado el segundo parámetro a las funciones porque necesitaba parámetros en este formato pageSearch[li_date][datefrom] y pageSearch[li_date][dateto]
Pero la label del segundo parámetro siempre permanece sin definir. Por favor, sugiera lo que está mal aquí?
Objeto JavaScript para probar la función:
{ "pageSearch": { "id": "", "agent_name": "", "access": "", "li_date": { "datefrom": "04/28/2022 02:15 PM", "dateto": "04/28/2022 02:15 PM" }, "email": "", "phone": "", "date": { "datefrom": "04/28/2022 02:15 PM", "dateto": "04/28/2022 02:15 PM" }, }}
¿Por qué no simplemente haces
url = "http//someurl/?obj=" + encodeURIComponent(JSON.stringify(myObject));y por otro lado lo decodificas así:
const myObj = JSON.parse(new URLSearchParams(window.location.search).get("obj"))