I needed to convert an object to query parameters
I have used the code suggested here for the recursive function
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("&");
};
I have added the 2nd parameter to the functions because I needed parameters in this format pageSearch[li_date][datefrom]
and pageSearch[li_date][dateto]
But the 2nd parameter label
always remains undefined. Please suggest what's wrong here?
JavaScript Object for testing the function:
{
"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"
},
}
}