Breaking apart values separated by semicolons in JavaScript to create separate rows with additional information

Here is the provided data:

result =

    [  
       {  
          "Id":"0012v00002InPVmAAN",
          "Test__c":"India; Africa; Mombasa",
          "Test1__c":"AFR; TFR; GFR"
       }
    ]

I want to convert the above data into a CSV file by splitting the semicolon separated values (Test__c & Test1__c) into multiple rows along with other data.

"Id,Test__c,Test1__c --> csv file column header
"0012v00002InPVmAAN","India","AFR"
"0012v00002InPVmAAN","Africa","TFR"
"0012v00002InPVmAAN","Mombasa","GFR"

In JavaScript -

this.data = result
downloadCSVFile() {
        let rowEnd = '\n';
        let csvString = '';
        // This set eliminates any duplicate keys
        let rowData = new Set();
        
        this.data.forEach(function (record) {
            Object.keys(record).forEach(function (key) {
                rowData.add(key);
            });
        });

        rowData = Array.from(rowData);

        csvString += rowData.join(',');
        csvString += rowEnd;

        for (let i = 0; i < this.data.length; i++) {
            let colValue = 0;

            for (let key in rowData) {
                if (rowData.hasOwnProperty(key)) {
                    let rowKey = rowData[key];
                    
                    if (colValue > 0) {
                        csvString += ',';
                    }

                    let value = this.data[i][rowKey] === undefined ? '' : this.data[i][rowKey];
                    csvString += '"' + value + '"';
                    colValue++;
                }
            }
            csvString += rowEnd;
        }

I attempted the code above, but it is combining (Test__c & Test1__c) values into a single row.

How can I properly create a CSV file by splitting the semicolon separated values (Test__c & Test1__c) into multiple rows along with other data?

Answer №1

In this updated version, the downloadCSVFile function has been removed and replaced with result. If the field names ('Id', 'Test__c', 'Test1__c') remain constant, you can simplify the second part of your code:

const result = [
  {
    Id: "0012v00002InPVmAAN",
    Test__c: "India; Africa; Mombasa",
    Test1__c: "AFR; TFR; GFR"
  }
];

result.map(item => {});

let rowEnd = "\n";
let csvString = "";
// using a set to eliminate duplicates in keys
let rowData = new Set();
// extracting keys from data
result.forEach(function(record) {
  Object.keys(record).forEach(function(key) {
    rowData.add(key);
  });
});
// converting set to array
rowData = Array.from(rowData);

// separating values with ','
csvString += rowData.join(",");
csvString += rowEnd;

const lines = [];

lines.push(rowData.join(","));

result
  .reduce((acc, { Id, Test__c, Test1__c }) => {
    const a = Test__c.split(";");
    const b = Test1__c.split(";");
    a.forEach((item, index) => {
      acc.push({ Id, Test__c: item, Test1__c: b[index] });
    });
    return acc;
  }, [])
  .forEach(item => {
    lines.push(rowData.map(key => item[key]).join(","));
  });

csvString = lines.join(rowEnd);

console.log(csvString);

// Id,Test__c,Test1__c
// 0012v00002InPVmAAN,India,AFR
// 0012v00002InPVmAAN, Africa, TFR
// 0012v00002InPVmAAN, Mombasa, GFR

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

What is the best way to turn off default CSS styling in KendoUI?

I am facing an issue in my application where I am using global CSS definitions for "INPUT", "SELECT", and other elements. The problem arises when I try to incorporate KendoUI widgets, as they override my default CSS styles. For instance, my CSS code looks ...

Picture is not showing up on my MVC software

Within a table containing multiple other tds, I am having an image tag. <table class="MyClass"> <tr> <td> @Html.LabelFor(m => m.ShopName) </td> <td> @Html.TextBoxFor(mode ...

Steps on how to set the values of a select option based on a JSON parsed array

After receiving an array from a JSON call, I am trying to populate a select element with the data. {1:Android, 2:IOS, 3:Business Management Systems, 4:Database, 5:Codes/Scripts, 6:Others} or 1: "Android" 2: "IOS" 3: "Business Management Systems" 4: "Da ...

What is the best way to execute individual API requests for various sheets within the same spreadsheet?

I am currently working on integrating the Google Sheets API with Node.js. I need assistance with understanding the correct syntax for calling two separate sheets within one spreadsheet. After reaching out to chatgpt and gemini, I received conflicting answe ...

Why does my script seem to be missing from this GET request?

Encountering an issue while setting up a page using npm and grunt. Request URL:http://localhost:9997/bower_components/requirejs/require.js Request Method:GET Status Code:404 Not Found The problematic html code is as follows: <script> ...

org.openqa.selenium.WebDriverException: unexpected issue: Chrome failed to initiate: crashed.(chrome inaccessible)

Having issues running Java script (selenium framework) on Chrome. Tried various solutions but still facing problems: Unchecked run as admin Added arguments Snippet of the code: ChromeOptions options = new ChromeOptions(); //options.setExperimentalOption ...

What is the best way to transfer a JavaScript object with string values containing quotes from node.js to the browser?

I have a node/express application and need to send a JavaScript object to the browser. Currently, I achieve this by using JSON.stringify on the object and then embedding it into the HTML: In my Node.js/Express code: var myObject = /* fetched from databas ...

Running JavaScript in selenium and obtaining the result

I'm currently utilizing JavaScript with Selenium WebDriver. Here is a snippet of my code: let return_value = driver.execute_script(script) However, I am unsure how to retrieve the value from my script. const token = await grecaptcha.enterprise.exec ...

React Array Not Behaving Properly When Checkbox Unchecked and Item Removed

When using my React Table, I encountered an issue with checkboxes. Each time I check a box, I aim to add the corresponding Id to an empty array and remove it when unchecked. However, the current implementation is not functioning as expected. On the first c ...

Conflicting issues with jQuery's load() method

I am facing an issue with loading two HTML pages into a single div. I have index.html and try.html in the root folder, where try.html is loaded into index.html's div (#content) when Button 01 is clicked on index.html. The problem arises when I further ...

Formulation, on the other side of the comma

I have a calculation script that is almost working perfectly, but it seems to be ignoring values with decimal points. Can anyone offer some guidance on how to fix this issue? var selects = $('select'); var inputs = $('input'); selects. ...

Learn to save Canvas graphics as an image file with the powerful combination of fabric.js and React

I am currently utilizing fabric.js in a React application. I encountered an issue while attempting to export the entire canvas as an image, outlined below: The canvas resets after clicking the export button. When zoomed or panned, I am unable to export co ...

Unable to forward to another page using NodeJS (Express)

After spending a considerable amount of time trying to find a solution, I finally managed to create a simple button click redirection using NodeJS and Express. However, when clicking on the "Next page" button in my index.html file, I encountered an error s ...

When you add a new library using npm and it has a dependency on another existing library, it could potentially cause conflicts or issues with

After successfully installing a library, I am now looking to install another library that relies on the first one. I have some uncertainty about what will occur: The second library will utilize the shared library already installed for its functionality ...

How can I retrieve the array data that was sent as a Promise?

I have a database backend connected to mongoDB using mongoose. There is a controller that sends user data in a specific format: const db = require("../../auth/models"); const User = db.user const addProduct = (req, res) => { User.findOne({ ...

How can I transfer Gmail message using express rendering parameters?

Using passport-google-oauth for authentication and the node-gmail-api for fetching gmail, I aim to display gmail message after authentication. In order to achieve this, I have written the following code in routes.js: app.get('/profile', isLogged ...

Challenges with handling callbacks in Javascript

I'm currently working on creating a user-friendly GUI using the w2ui library, but I've encountered an issue with integrating a toolbar into my main layout. The problem arises when the toolbar is added before the layout is fully constructed. Sinc ...

Establishing the httppostedfilebase variable when validation is unsuccessful in an ASP.Net MVC view

I'm currently facing an issue with handling validation errors in my application. I have implemented uploading and downloading images successfully, but when there are validation errors and the controller redirects back to the page, the HttpPostedFileBa ...

Make an angularJS PUT request using $http

After selecting a value from the dropdown selection, I am attempting to make a PUT call in AngularJS. Although I have successfully retrieved the value from the selection, I am encountering difficulty in generating the response for the PUT call. Below is t ...

What is the difference between using array pointers and vectors in C++?

Similar Query: Exploring the performance gap between arrays and std::vectors in C++ I am curious to determine which option is faster and consumes fewer resources. I tend to believe that vectors are more dependable and secure, while pointers to arrays ...