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

76
Views
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 answers
Answer question

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 Report

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 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!