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}]}
Lexy Feito
  • 280
  • 1
  • 8
  • 19
  • 1
    Does this answer your question? [How to convert URL parameters to a JavaScript object?](https://stackoverflow.com/questions/8648892/how-to-convert-url-parameters-to-a-javascript-object) – evolutionxbox Dec 22 '21 at 14:37

1 Answers1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392