Parse specific string into object

Is there a javascript library out there that would parse this type=1&merchant[type]=1&member[0][type]=1 into an object. The result would look like:

{type:1, merchant: {type: 1}, member: [{type: 1}]}

>Solution :

You could split the string into parts of keys and values anbuild a new object by looking to the following property of creating an array or an object for the actual level of a nested structure.

At the end assign the value to the last property.

const
    setValue = (object, path, value) => {
        const
            keys = path.replace(/[\[]/gm, '.').replace(/[\]]/gm, '').split('.'),
            last = keys.pop();

        keys
            .reduce((o, k, i, kk) =>  o[k] ??= (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}), object)
            [last] = isFinite(value) ? +value : value;
    },
    string = 'type=1&merchant[type]=1&member[0][type]=1',
    result = string.split('&').reduce((r, pair) => {
        setValue(r, ...pair.split('='));
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Leave a Reply