Converting a CSV string into an array only when there is a line break in the body

Need help to convert a CSV string into an array of array of objects. Struggling with handling \n in the incoming request, causing issues with splitting and code errors. The string format includes messages enclosed in ".

"id,urn,title,body,risk,s.0.id,s.1.id,s.2.id,a.0.id,a.1.id,a.2.id,a.3.id
302,25,\"Secure Data\",\"Banking can save a lot of time but it’s not without risks...

Attempting to organize this content from CSV string into an array for better manipulation. Here is the initial approach:

function csv_To_Array(str, delimiter = ",") {
      const header_cols = str.slice(0, str.indexOf("\n")).split(delimiter);
      const row_data = str.slice(str.indexOf("\n") + 1).split("\n");
      const arr = row_data.map(function (row) {
        const values = row.split(delimiter);
        const el = header_cols.reduce(function (object, header, index) {
          object[header] = values[index];
          return object;
        }, {});
        return el;
      });

      // return the array
      return arr;
    }

Considering using regex to handle splitting based on commas or \n characters, taking care if there are additional " symbols within the text:

array.split(/,/\n(?!\d)/))

Answer №1

Give this a try:

    csvData.replace(/(\r\n|\n|\r)/gm, "");

After removing new lines with the above code snippet, you can use the following code to start building an array from the modified CSV string:

  const createArrayFromCsv = () => {
    const individualCharacters = csvData.split(""); // <-- resulting in a new array 
    console.log(individualCharacters);

    const commaSeparatedValues = csvData.split(",");
    console.log(commaSeparatedValues);
  }

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

JSON input that appears to be correct but unexpectedly ends

I'm currently coding a discord bot and came across this snippet: function addFunds(id, amount){ accounts = fs.readFileSync("accounts.data", 'utf8'); console.log(JSON.parse(accounts)) var obj = JSON.parse(accounts); var i; for (i in ...

Fresh React framework

I haven't worked on a React app in a while, but when I decided to start a new one and import my old function, I encountered the following error: C:/Users/Hello/Documents/Dev/contacts/client/src/App.tsx TypeScript error in C:/Users/Hello/Documents/Dev ...

The switch statement remains unchanged for varying variables

Here is some code that I am working with: updateTable(selectedIndex) { console.log("running updateTable function"); let level = ''; // if (selectedIndex == 1){ // this.setState({level: 'day'}) // th ...

Having trouble with React Page crashing when trying to access the component state

I'm attempting to create a side-bar menu that swaps out content in a <main> tag when menu buttons are clicked. However, I'm facing an issue where the page becomes unresponsive and eventually crashes due to React issues while trying to read ...

Retrieve an array of objects by matching a specific object id

Seeking assistance for a React project centered around a quiz application. Within my database (currently utilizing Firebase Realtime Database), I have a collection of questions and another collection of answers. Questions are identified by an Id, title, an ...

What is the reason for memory allocation only occurring when geometry.elementsNeedUpdate is used?

When using a basic animate function like this: function animate() { geometry.elementsNeedUpdate = true; requestAnimationFrame( animate ); renderer.render( scene, camera ); } A memory allocation occurs even if no elements are changed. To address this, I ...

Oops! Looks like there was an issue during the testing process with Postman

Encountering an issue during the API testing using Postman with error messages like "something went wrong" authRoute.js In the authRoute file, I have implemented the application logic. I need assistance in resolving the error. Additionally, I have attach ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

php working with indexed arrays and applying filters

I'm facing a challenge with manipulating an array and need some help. Here's the situation summarized: Starting with a string like this: $testString = 'John doe 123 Main st 77555'; My goal is to break it into 3 main parts: $fname = &a ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Unique: "Best Practices for Setting Angular.js Controller Data Directly in the Code"

In this scenario, I need to initialize the data from an inline script, even though I know how to achieve this using a promise on an http request. Currently, the controller is already defined in the header js: var testModule = angular.module('myTestM ...

Is it possible to use file upload for sending via Ajax's POST method?

Let's talk about the scenario at hand Here's what happens in a single form: 1) The user clicks on the 'browse' button, which opens a dialog to select an image file for uploading. Example: input id='img_upload' name="ufile" ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...

The request body is not showing up as a key-value pair, while the request headers and other parameters are visible

Example of 'Advanced REST Client' Request I am currently using Postman and Advanced REST client to create a simple POST request based on the code below: 'use strict'; var express = require('express'); var bodyParser = requir ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

In C++, JSON only permits a single top-level item

It seems that my object creation code is not working properly, despite referring to numerous examples. I am combining the "Staff" label with Staff ID for easy reference later on. The contents of the json object depend on user input. I am utilizing the nlo ...

Using ngFor in Angular 2-5 without the need for a div container wrapping

Using ngFor in a div to display an object containing HTML from an array collection. However, I want the object with the HTML node (HTMLElement) to be displayed without being wrapped in a div as specified by the ngFor Directive. Below is my HTML code snipp ...

Using Node.js to import modules that have been webpacked

I'm faced with the challenge of managing a multitude of files that come along when installing various modules using npm install, each with its own dependencies. To simplify this process, I am considering consolidating all required libraries using web ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

What is the best way to reset the scroll position of a div when you stop hovering over a link?

Can anyone help me figure out how to reset the scroll wheel when hovering over dropdown menu items? I've tried multiple solutions found online, but none seem to be working for me. If you have any ideas on how to accomplish this, please let me know! f ...