Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
Tratando de transformar esta cadena en un objeto

tengo esta cadena:

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

Me gustaría transformarlo en un objeto:

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

¿Cómo puedo hacer esto?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Dado que la cadena será válida con el formato especificado:

Puede dividir la cadena en pares de elementos de lista clave. Luego, itere sobre ellos e inserte cada uno en un objeto de la siguiente manera:

 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 Report

0

Este fragmento funciona hasta que trabaja con un objeto de 1 nivel. Si necesita analizar un objeto anidado, debe refactorizarlo ligeramente.

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

De todos modos, no sé cuál es el beneficio de tratar con esta notación.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!