"Import data from a text file and store it as an array of objects using Types

I need assistance with converting the information in my text file into an array of objects. Below is a snippet of the data from the text file:

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

Currently, this is my code implementation:

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

The desired output format I am aiming for is as follows:

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

Answer №1

If you want to extract data from a structured text file, one approach is to use regular expressions (regex) to split the content by new lines and then further divide each line into individual words based on spaces. Finally, you can organize this information under appropriate headings using the reduce() function in JavaScript.

const sampleText = `
  ID   NAME   AGE   CITY
  1    John   25    New York
  2    Sara   30    Chicago
`;

// Split the text by newline characters
const lines = sampleText.trim().split(/\n/g);

// Separate each line into words based on spaces
const wordsPerLine = lines.map(line => line.trim().split(/\s+/g));

// The first line contains the headings
const headings = wordsPerLine.shift();

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

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The callback functions, such as afterMove, are not being executed

This code snippet is copied from Owl Carousel's official website. I am having trouble getting the callback functions like afterMove to work. Can anyone help me figure out why the afterMove function is not being called? It seems that none of the callba ...

Looking to disable the back button in the browser using next.js?

How can I prevent the browser's back button from working in next.js? // not blocked... Router.onRouteChangeStart = (url) => { return false; }; Does anyone know of a way to disable the browser's back button in next.js? ...

I am creating accordion-style bootstrap tables using data generated from an ng-repeat loop, all without the use of ui.bootstrap or jquery

My attempt at creating a table with rows filled using ng-repeat is not working as expected. I want a collapsible panel (accordion) to appear on click of each row, but only a single row is rendering with my current code. Here is a link to my code: var ap ...

Having trouble retrieving parameters within the expressjs router.delete endpoint implementation

Check out my code snippet below where I utilized Express router and Mongoose Model. I am encountering an issue accessing the id parameter. router.delete('/task/:id', function (req, res) { Task.remove({ ...

What are the methods for choosing various boxes using the UP/DOWN/RIGHT/LEFT arrow keys?

This code snippet displays a 3x3 matrix where boxes can be hovered over and selected. The goal is to navigate around with keys and select boxes using ENTER. Can anyone provide guidance on how to achieve this functionality? <link rel="stylesheet" href ...

Discovering necessary information by iterating through JSON

Being new to vue js, my goal is to loop through the provided JSON data and check if the required data is present within the file. Here is a snippet of the JSON: [ { "id": "text-5", "widget": "hello", "params": { "0": "section-right", ...

Material-UI: The call stack has exceeded the maximum range, causing an Uncaught RangeError

I am currently utilizing the Dialog and Select components offered by Material-UI in conjunction with React. Here is a quick example: import React from 'react'; import { Dialog, MenuItem, Select } from '@material-ui/core'; class Examp ...

Leveraging various techniques within a single controller in AngularJS

I am seeking assistance and advice on a coding issue I am facing. I am attempting to use two methods in one controller. The first method is to display selected rooms, while the second method is to display selected pax. However, only the first method seems ...

A guide on efficiently traversing a disk directory, recursively fetching all paths in relative format, and converting them into a JSON stream with node.js

My goal is to traverse a directory tree and store it in a JSON file using node.js with the following approach: Open specified directory Convert paths into a relative format. For example: Directory: C:/test { {"C:/test folder 1": [ {"folder 1": ["fil ...

Assistance needed for jQuery functions running too early

Within my click function, I am setting certain flags and then calling two functions. However, I want these two functions to execute sequentially in order after the flags have been set. jQuery("#element").click(function(e){ var op = jQuery("#box" ...

lint-staged executes various commands based on the specific folder

Within my project folder, I have organized the structure with two subfolders: frontend and backend to contain their respective codebases. Here is how the root folder is set up: - backend - package.json - other backend code files - frontend - p ...

The onchange() function for a multi-checkbox dropdown is failing to work as

Issue with Multiple Drop Down Checkbox Functionality: The first parameter is always received as undefined, and the onchange event only captures the value of the first checkbox selected. <select name="multicheckbox[]" multiple="multiple" class="4colacti ...

Utilizing HTML5/JavaScript to send a text message from a mobile device

I am developing a mobile web application to be downloaded from various markets with a mini web server, capable of running on any operating system such as iOS, Android, Windows8, and more. My goal is to make the application as OS-independent as possible by ...

When a text is wrapped by an HTML div using absolute positioning, is there a way to prevent it from wrapping without relying on white space

I have a group of div elements positioned absolutely on the screen. If any div contains content that is too big for the screen, the browser wraps it into multiple lines to fit. However, I do not want this behavior. Instead, I want the overflowing content ...

Tips for extracting the values of multiple input fields in JavaScript and displaying them on a webpage

I want to collect all the values from input fields and display them on the website. Check out my code snippet below: var button = document.querySelector("button"); button.addEventListener("click", function() { var inputs = document.querySelectorAll( ...

Steps to retrieve a date from a form control

html <form [formGroup]="searchForm" (ngSubmit)="search()"> <div class="row"> <div class="col"> <input type="date" class="form-control" formControlName="startD ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic! generalArray = [{name:String, ...

I'm looking to enhance security in my sign-up form by adding a custom shield using Angular for my Firebase database. How can

I recently followed a tutorial to build my angular app with firebase authentication. Currently, everything is functioning correctly. However, This is the first time I am attempting to create a genuine sign-up form with custom fields and integrate them i ...

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...