2

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 Answer 1

4

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer! but i am getting some extra empty indexes. Can you help me on this?
@UsamaTariq Sure, can you update your snippet with what you've tried? Please also include the output of your txtData variable so i know how the data looks that you are trying to parse.
@UsamaTariq I also added some trim() functions to my snippet, maybe this will help remove leftover spaces which can cause empty indexes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.