skip to Main Content

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

const rawList = `*******Arn*******Brn*******Crn*******D`
const dataList = rawList.split('rn');
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"] …

2

Answers


  1. 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'] ]
    
    Login or Signup to reply.
  2. Several issues, you just split and then stringify the result.

    Here is a split and a push to new arrays

    const rawList = `*******Arn*******Brn*******Crn*******Drn*******E`;
    const masterList = [];
    const dataList = rawList.split('rn');
    let cnt = 0;
    for (let i = 0; i < dataList.length; i++) {
      if (i > 0 && i%2===0) cnt++; // increment the index
      masterList[cnt] ??= []; // create a new array every second element
      masterList[cnt].push(dataList[i]);
    }
    console.log(JSON.stringify(masterList))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search