2

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}]}
1

1 Answer 1

2

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;

        return object;
    },
    string = 'type=1&merchant[type]=1&member[0][type]=1',
    result = string
        .split('&')
        .reduce((r, pair) => setValue(r, ...pair.split('=')), {});

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

Sign up to request clarification or add additional context in comments.

Comments

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.