Convert a query string with array to object with Javascript

Asked

Viewed 17 times

0

Hello :)

I have a query string that I would like to transform into object, but this query string has an array that is converted as follows:

&meuArray[0]=17&meuArray[1]=1

When I convert this part back to object it does not return me the array I need to use to work in other project situations, which would be:

meuArray(2)
meuArray {
0:17,
1:1
}

But yes:

meuArray[0]: "17"
meuArray[1]: "1"

The function I’m using to convert the query string into object is:

export const convertQueryStringToObject = (query) => query && query.replace('?', '').split('&').reduce((obj, val) => {
    if (!val) return obj;
    if (val.includes('.')) {
        const interno = val.split('.').reduceRight((subObj, subVal, idx, arrName) => {
            if (arrName.length - 1 === idx) {
                const [name, value] = subVal.split('=');
                return ({ [name]: decodeURI(value) });
            }
            if (obj[subVal]) {
                return { ...obj, [subVal]: { ...obj[subVal], ...subObj } };
            }
            return { [subVal]: { ...subObj } };
        }, { obj });
        return { ...obj, ...interno };
    }
    const [name, value] = val.split('=');
    return { ...obj, [name]: value };
}, {});

What I can do to improve it and bring the formatted array the way I need it?

  • Of the options indicated in the link above, I would use that one, indicating the use of URLSearchParams (already has a good support of most browsers, except the deceased IE - in the specific case of this, there are other solutions there, which can also serve)

  • But if the idea is just to create an object from the parameters, it can simply be var params = new URLSearchParams('&meuArray[0]=17&meuArray[1]=1'); and then var obj = Object.fromEntries(params.entries()); to create the object. Use reduce, inclusive, is an exaggeration in this case (incidentally, in most cases is an exaggeration, I don’t understand this fixation on using reduce for everything, even when he is no longer suitable...)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.