Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i get value of list every 2 lines and so on to json (JavaScript)

I have a list of names into text file and i need to convert to json every 2 lines .

const rawList = `*******A\r\n*******B\r\n*******C\r\n*******D`
const dataList = rawList.split('\r\n');
for (i = 0; i < dataList.length; i++) {
  var masterlist = JSON.stringify(dataList[i]);
  console.log(masterlist)
}

Output :
"*******A"
"*******B"
"*******C"
"*******D"

What i need:
["*******A","*******B"]
["*******C","*******D"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

let say you store all of Output in an array called arr

const arr = ['a','b','c','d', 'e', 'f', 'g']

const chunks = []
const chunkSize = 2;
for (let i = 0; i < arr.length; i += chunkSize) {
    const chunk = arr.slice(i, i + chunkSize);
    chunks.push(chunk)
}

console.log(chunks) // [ ['a', 'b'], ['c', 'd'], ['e', 'f'], ['g'] ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading