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

167
Views
Convert plain text data into an object with arrays based on formatting

What is the best way to convert plain text data like:

[group a]
a
b
c
[group b]
a
d
f

Into an object...

{
groupA: ['a', 'b', 'c'],
groupB: ['a', 'd', 'f']
}

The plain text data will vary in length, but the structure will always be represented like:

[parent group]
child item 1
child item 2
...
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use split and reduce

const string = `[group a]
a
b
c
[group b]
a
d
f`

const list = string.split(`\n`)
let saveKey;
const obj = list.reduce((acc,cur) => {
  if (cur.startsWith('[')) { 
    const groupLetter = cur.match(/ (\w+)\]/)[1].toUpperCase()

    saveKey = `group${groupLetter}`;
    acc[saveKey]=[];
  }  
  else {
    acc[saveKey].push(cur);
  }  
  return acc
},{})
console.log(obj)

about 4 years ago · Juan Pablo Isaza Report

0

You can grab all the lines of text and reduce the lines by parsing and determining if it is a key or a value. Your accumulator needs to store both the results and the current key.

const
  parse = (text) =>
    text.trim().split('\n')
    .reduce((acc, line) => {
      const match = line.trim().match(/^\[(.+)\]$/);
      return match
        ? { ...acc, key: match[1] }
        : { ...acc, result: { ...acc.result,
            [acc.key]: [...(acc.result[acc.key] ?? []), line.trim()] }
          };
    }, { result: {}, key: null }).result,
  data = parse(document.querySelector('#data').value);

console.log(data);
.as-console-wrapper { top: 0; max-height: 100% !important; }

#data { display: none; }
<textarea id="data">[group a]
a
b
c
[group b]
a
d
f</textarea>

about 4 years ago · Juan Pablo Isaza Report

0

Make an array of the original string by splitting on \n, then loop through and create the object:

const str = `[group a]
a
b
c
[group b]
a
d
f`

const arr = str.split('\n')
const obj = {}
let curHeader

arr.forEach(el =>
{
  if(el[0] === '[')
  {
    let frmtEl = el.substring(1, el.length-1)
    let frmtElArr = frmtEl.split(' ')
    curHeader = frmtElArr[0] + frmtElArr[1].toUpperCase()
    obj[curHeader] = []
  }
  else
  {
    obj[curHeader].push(el)
  }
})

console.log(obj)

about 4 years ago · Juan Pablo Isaza 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!