Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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}]}
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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; }

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda