Read text file into array of objects in Typescript

Viewed 1673

I want to convert the data in my text file into an array of objects, here is my data in text file:

DOCNO   NETAMOUNT   IREF1   IREF2   DOCDT
001 30000   50  100 6/7/2020
2   40000   40  90  6/7/2020

Here is my code as for now:

  reader.onload = (ev)=>{
        const data = reader.result;
        var txtData = data.toString()
        console.log(data,"txt data")
        var lines = txtData.split(' ');
        for(var line = 0; line < lines.length; line++){
            console.log(lines[line]);
        }
    
     };
    
     reader.readAsText(file)
}

I want to convert into a format like this:

0: {DOCNO: "001", NETAMOUNT: "30000", IREF1: "50", IREF2: "100", DOCDT: "6/7/20"}

1: {DOCNO: "2", NETAMOUNT: "40000", IREF1: "40", IREF2: "90", DOCDT: "6/7/20"}

1 Answers

You can use regex to split the data by new line. After that split each line by spaces to get the words. At last map all the data to the right heading with reduce().

const fakeFile = `
  DOCNO   NETAMOUNT   IREF1   IREF2   DOCDT
  001 30000   50  100 6/7/2020
  2   40000   40  90  6/7/2020
`;

// Split data by newline character
const lines = fakeFile.trim().split(/\n/g);

// Split data by spaces (one or more)
const wordsPerLine = lines.map(line => line.trim().split(/\s+/g));

// First line are the headings
const headings = wordsPerLine.shift();

// Combine lines with heading
const result = wordsPerLine.reduce((all, line) => {
  const obj = {};
  
  line.forEach((word, index) => {
    obj[headings[index]] = word;
  });
  
  all.push(obj);
  
  return all;
}, []);

console.log(result);

Related