2

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"
2
  • is that a single string? and what have you tried so far ? Commented Feb 16, 2021 at 11:29
  • yes it is a string string. when i import the csv file i am using filereader. so i am getting this string Commented Feb 16, 2021 at 11:30

3 Answers 3

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/

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

Comments

1

    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

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.