how should we convert string data into array and display into react table

I have imported CSV data and converted into the following stringData. Now I have to display this stringData in a React table. I have tried using map function to separate the headers and map to <th> but when I tried to display the values into <tr> it is considering each row as one value. Please let me know if there is any other way of doing this. Thanks

const stringData = "BRANCH,ITEMNUM,UNITCOST,COSTMETHOD
34,130156,86.25,51
34,220134,75.8425,51
34,190365,53.5325,51
34,200350,18.4,51"

3 thoughts on “how should we convert string data into array and display into react table”

  1. You just have to split twice 1st you have to do it by space and then you have to split it by ,

    Then you can build your table

    const stringData = "BRANCH,ITEMNUM,UNITCOST,COSTMETHOD 34,130156,86.25,51 34,220134,75.8425,51 34,190365,53.5325,51 34,200350,18.4,51"
    var res = stringData.split(" ");
    var test = document.getElementById("test");
    res.map((items) => {
      let row = items.split(",");
       var trBlock = document.createElement("tr")
       row.map((item) => {
         trBlock.innerHTML += `
            <td>${item}</td>
         `
        test.appendChild(trBlock)
       })
    })
    table, th, td {
      border: 1px solid black;
    }
    <table id="test"></table>
    Reply
  2. Assuming your string of results includes line breaks to indicate different rows, this solution should work:

    const stringData = `BRANCH,ITEMNUM,UNITCOST,COSTMETHOD
    34,130156,86.25,51
    34,220134,75.8425,51
    34,190365,53.5325,51
    34,200350,18.4,51`;
    
    const rows = stringData.split('\n');
    let cols = rows.splice(0, 1)[0];
    cols = cols.split(',');
    
    const result = rows.map((row) => {
      const vals = row.split(',');
      return vals.reduce((res, val, idx) => {
        const prop = cols[idx];
        res[prop] = val;
        return res;
      }, {});
    });
    
    console.log(result);
    

    Here’s a working JSFiddle: https://jsfiddle.net/hannahska/y4rq13h8/8/

    Reply
  3.     const stringData = `BRANCH,ITEMNUM,UNITCOST,COSTMETHOD
        34,130156,86.25,51
        34,220134,75.8425,51
        34,190365,53.5325,51
        34,200350,18.4,51`;
        
        let lines = stringData.split("\n");
        
        let header = lines[0].split(",");
        
        let body = lines.filter((item) => item !== header).map(item => item.split(","));
    
        console.log({header, body});

    Explanation:

    1. Our starting point is the string you have
    2. We break up the string into lines, \n is the newline character, we use it as a separator that denotes the end of a line and the start of the next
    3. Header is the very first line
    4. Body is all the lines except the header
    5. We split each line into items, using , as the separator
    Reply

Leave a Comment