Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading