'Serialise an Object into a list of URL query parameters?

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"
    },

}

}



Solution 1:[1]

Why don't you just do

url = "http//someurl/?obj=" + encodeURIComponent(JSON.stringify(myObject));

and on the other side you decode it like this:

const myObj = JSON.parse(new URLSearchParams(window.location.search).get("obj"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lviggiani