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

Advertisements

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"]

>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'] ]

Leave a ReplyCancel reply