2

I have a react app that handles routing in the application. I am getting json object from db with parameters that will look like this:

    let paramsObj = {
        state: {
            Corp: "CorpCode",
            Location: "LocationCode",
            IsCorp: false
        }
    };

How to convert paramsObj and encode it to URL parameters so the final string would look like this?state=%7B%20Corp%3A%20%22CorpCode%22%2C%20Location%3A%20%22LocationCode%22%2C%20IsCorp%3A%20false%20%7D

1 Answer 1

1
let paramsObj = {
    state: {
        Corp: 'CorpCode',
        Location: 'LocationCode',
        IsCorp: false,
    },
};

const urlSearchParams = Object.keys(paramsObj).reduce((output, key) => {
    const value = paramsObj[key];
    const valueString = JSON.stringify(value);
    output.append(key, valueString);
    return output;
}, new URLSearchParams());

console.log(urlSearchParams.toString());
Sign up to request clarification or add additional context in comments.

4 Comments

It should work somehow in combination new URLSearchParams().toString(). your solution gives me link without "state=" part which should be taken from json object
You can do it with reduce as seen now
Is it ok that in this solution string is URI encoded two times? Like: 1.%7B%20Corp%3A%20%22CorpCode%22%2C%20Location%3A%20%22LocationCode%22%2C%20IsCorp%3A%20false%20%7D 2.%257B%2520Corp%253A%2520%2522CorpCode%2522%252C%2520Location%253A%2520%2522LocationCode%2522%252C%2520IsCorp%253A%2520false%2520%257D
You are right, it was a mistake, the encodeURIComponent encoding I added was redundant and is handled by URLSearchParams. I fixed the code block in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.