我从CSV文件获取一个数组中的逗号分隔值,并使用它在React中显示表格。
[
"Company,Industry,Years,CEO",
"Tesla,Automobile,15,Elon",
"SpaceX,AeroSpace,17,Elon",
"Amazon,Software,24,Jeff",
"Google,Software,20,Sundar",
"Microsoft,Software,30,Satya",
"BMW,Automobile,103,Harald",
"BlueOrigin,AeroSpace,19,Jeff",
"NASA,Space,61,Gov",
"Hyperloop,Transportation,5,Elon"
]
JSX
renderCsvTable() {
const { file } = this.state;
if(file !== "") {
let data = `<table className="csv-table">`;
file.forEach((cells, i) => {
let cell_data = cells.split(',');
data+= `<tr>`;
cell_data.forEach((column) => {
if (i === 0) {
data+= `<th>${column}</th>`;
} else {
data+= `<td>${column}</td>`;
}
});
data+= `</tr>`;
});
data+= `</table>`;
return (
<div>{ parse(data) }</div>
)
}
}
我想根据单独的列对数组进行排序。
目前,我可以使用排序方法按第一列进行排序
this.state.file.sort((a, b) => (a > b) - (a < b));
但是它也正在对数组中的[0] index
进行排序,因为它是表的标题,所以我不想对它进行排序。
排序后
[
"Amazon,Software,20,Jeff",
"BMW,Automobile,33,Harald",
"BlueOrigin,Space,4,Jeff",
"Company,Industry,Years,CEO",
"Google,Software,30,Sundar",
"Hyperloop,Transportation,5,Elon",
"Microsoft,Software,30,Satya",
"NASA,Space,60,Gov",
"SpaceX,Space,5,Elon",
"Tesla,Automobile,10,Elon"
]
我还想对列进行明智的排序,例如,如果单击年份或 CEO ,则应该按年份或CEO进行排序。每列都一样。
答案 0 :(得分:1)
这是您的方法。
slice(1)
获取除标题以外的所有行sort()
返回的行上应用slice(1)
colno
。sort()
中,您应该比较colno
上的值arr[0]
添加到已排序的数组之前。
let arr = [
"Company,Industry,Years,CEO",
"Tesla,Automobile,15,Elon",
"SpaceX,AeroSpace,17,Elon",
"Amazon,Software,24,Jeff",
"Google,Software,20,Sundar",
"Microsoft,Software,30,Satya",
"BMW,Automobile,103,Harald",
"BlueOrigin,AeroSpace,19,Jeff",
"NASA,Space,61,Gov",
"Hyperloop,Transportation,5,Elon"
]
function sort(arr,colno){
let x = arr.map(x => x.split(',').map(a => Number(a) || a));
return [x[0]].concat(x.slice(1).sort((a,b) => {
if(typeof a[colno] === 'number'){
return a[colno] - b[colno];
}
else return a[colno].localeCompare(b[colno]);
})).map(x => x.join(','))
}
console.log(sort(arr,1))
答案 1 :(得分:1)
我建议在render()
函数中构建html元素。这样做将使您能够访问React的数据绑定和事件侦听语法,使其更易于维护并提高大型表的性能。
这可以通过将CSV数据解析为对象并将其存储到this.state.data
中来完成。密钥是标题,值是数据点。
this.state.data =[
{'Company':'Tesla','Industry':'Automobile','Years':'15','CEO':'Elon'},
{'Company':'SpaceX','Industry':'AeroSpace','Years':'17','CEO':'Elon'},
{'Company':'NASA','Industry':'Space','Years':'61','CEO':'Gov'}
];
// on click of table heading and pass the key to sort based on (ex. company)
sortBy(key) {
let arrayCopy = [...this.state.data];
arrayCopy.sort(this.compareBy(key));
this.setState({data: arrayCopy});
}
compareBy(key) {
return function (a, b) {
if (a[key] < b[key]) return -1;
if (a[key] > b[key]) return 1;
return 0;
};
}
这是我的解决方案:https://codepen.io/brettdawidowski/pen/drJEjb
我希望这会有所帮助!
// babel.js
/*
* Row Component
*/
const Row = (rows) => (
<tr>
{
// Maping the values of Object to HTML <td>
// **Note: Assuming the Keys/Values will persist in the same order
Object.values(rows).map((r) => <td>{r}</td>)
}
</tr>
);
/*
Table Component
*/
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
// Example Input:
// {'Company':'Tesla','Industry':'Automobile','Years':'15','CEO':'Elon'},
// {'Company':'SpaceX','Industry':'AeroSpace','Years':'17','CEO':'Elon'},
// {'Company':'NASA','Industry':'Space','Years':'61','CEO':'Gov'}
],
// Add service/ajax call to http GET request to fetch csv from server/back-end
file: [
"Company,Industry,Years,CEO",
"Tesla,Automobile,15,Elon",
"SpaceX,AeroSpace,17,Elon",
"Amazon,Software,24,Jeff",
"Google,Software,20,Sundar",
"Microsoft,Software,30,Satya",
"BMW,Automobile,103,Harald",
"BlueOrigin,AeroSpace,19,Jeff",
"NASA,Space,61,Gov",
"Hyperloop,Transportation,5,Elon"
]
};
this.parseCsv();
this.compareBy.bind(this);
this.sortBy.bind(this);
}
parseCsv() {
const { file } = this.state;
if(file !== "") {
// set headers from index 0
let headers = file[0].split(',').map(value => value);
// temp remove index 0 from For loop
file.slice(1).forEach((row) => {
let items = row.split(',');
let d = {};
items.forEach((item, index) => {
// parse Numbers for proper sorting ex. “3” -> 3
if(/^[0-9]+$/.test(item)) item = parseInt(item)
// key: Company, value: Tesla
d[headers[index]] = item;
// When complete parsing add to state.data
if(index + 1 === items.length) {
this.state.data.push(d);
console.log(JSON.stringify(d));
}
})
})
}
}
compareBy(key) {
return function (a, b) {
if (a[key] < b[key]) return -1;
if (a[key] > b[key]) return 1;
return 0;
};
}
sortBy(key) {
let arrayCopy = [...this.state.data];
arrayCopy.sort(this.compareBy(key));
this.setState({data: arrayCopy});
}
render() {
const headers = Object.keys(this.state.data[0])
const rows = this.state.data.map( (rowData) => <Row {...rowData} />);
return (
<table>
<thead>
<tr>
{
headers.map((h) => <th onClick={() => this.sortBy(h)}>{h}</th> )
}
</tr>
</thead>
<tbody>
{ rows }
</tbody>
</table>
);
}
}
/*
* Render Component
*/
ReactDOM.render(<Table />, document.getElementById('app'));
<!-- index.html -->
<div id="app"></div>