我从 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] 索引
进行排序,我不想这样做,因为它是表的标题。
排序后
[
"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"
]
我还想按列排序,如果我点击 Years 或 CEO 它应该按年或 CEO 排序。每一列都一样。
最佳答案
我建议在 render()
函数中构建 html 元素。这样做将使您能够访问 React 的数据绑定(bind)和事件监听语法,使其更易于维护,并提高大型表的性能。
这可以通过将 CSV 数据解析为对象并将其存储到 this.state.data
中来完成。键是 header ,值是数据点。
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>
关于javascript - 对不包括零索引的数组中的 CSV 字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154710/