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

77
Visualizações
Trying to transform this string to an object

I have this string:

posts{id,title},posts2{id,title}

I'd like to transform it to an object:

{
  posts: [
    'id', 
    'title'
  ],
  posts2: [
    'id', 
    'title'
  ]
}

How can I do this?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Given that the string will be valid with the specified format:

You can split the string into pairs of key - list items. Then, iterate over them and insert each into an object as follows:

const stringify = string => {
  const obj = {};
  if(string) {
    const pairs = string.substring(0,string.length-1).split('},');
    pairs.forEach(pair => {
      const [key,value] = pair.split('{');
      obj[key] = value.split(",").filter(String);
    });
  }
  return obj;
}

console.log( stringify('posts{id,title},posts2{id,title}') );
console.log( stringify('posts{id,title}') );
console.log( stringify('posts{}') );
console.log( stringify('') );

over 4 years ago · Santiago Trujillo Relatório

0

This snippet works until you work with a 1-level object. If you need to parse nested object, you've to slightly refactor it.

const input = 'posts{id,title},posts2{id,title}';

const parse = (input) => {
  return input
    .replaceAll('{', '[')
    .replaceAll('}', ']')
    .replaceAll('],', '] , ')
    .split(' , ')
    .reduce((_, item) => {
      const key = item.split('[')[0];
      const value = item
        .replace(`${key}[`, '')
        .replace(']', '')
        .split(',')
      return {
        ..._,
        [key]: value
      };
    }, {})
};

const parsed = parse(input);

Anyway I don't know what's the benefit of dealing with this notation.

over 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