Problem:
I am new in dealing with this, so probably this is trival task, but let me know if this question isnt necessary, I will cancel it.
In my front end, I have a api that will return my a string which is supposed to be a csv xlsc, after I call a api.
After that, I would like to show it on UI.
Problem in it
This is the example string I get from the response
'key,Asset Class,Benchmark Name,Benchmark Source
\r\n1001,Macro,US CSA,BLOOMBERG
\r\n1026,Equity,MSCI x USD,BLOOMBERG
\r\n1002,Equity,MSCI USD,BLOOMBERG\r\n'
There are 4 header, and there are 4 row of data As you can see, this is not something I could display it in table. I would like to ask how could I frame this data structure, so that it could be listed out. or at least like a table format
CodePudding user response:
Like mentioned in the other answer, the most intuitive way is by splitting the string. I made an react approach to this.
let data =
"key,Asset Class,Benchmark Name,Benchmark Source \r\n1001,Macro,US CSA,BLOOMBERG \r\n1026,Equity,MSCI x USD,BLOOMBERG \r\n1002,Equity,MSCI USD,BLOOMBERG\r\n";
data = data.slice(0, -2); // gets rid of the last "\r\n"
const rows = data.split(" \r\n").map((cols) => cols.split(","));
const Table = () => {
return (
<table>
<tbody>
{rows.map((cols, index) => (
<tr key={`row-${index}`}>
{cols.map((value) => (
<td key={value}>{value}</td>
))}
</tr>
))}
</tbody>
</table>
);
};
function App() {
return <Table />;
}
export default App;
CodePudding user response:
The most intuitive way is split string by line break for each row and by delimiter for each column then loop over it to create a table
here is a rendering in vanilla but it should also share the same idea with react
see a sample fiddler here
<div id="root">
<table>
<tbody id="tt"></tbody>
</table>
</div>
var f = `key,Asset Class,Benchmark Name,Benchmark Source
\r\n1001,Macro,US CSA,BLOOMBERG
\r\n1026,Equity,MSCI x USD,BLOOMBERG
\r\n1002,Equity,MSCI USD,BLOOMBERG\r\n`.split('\n\r')
const tt = document.getElementById('tt')
for (let line of f) {
const tr = document.createElement('tr')
tt.appendChild(tr)
for (let col of line.split(',')) {
const td = document.createElement('td')
td.innerText = col;
tr.appendChild(td)
}
}