Reputation: 2833
i'm using react-table in my project and i wonder how create headers dynamically with array.
in my component i have:
const columns = [
{Header: 'day', accessor: ''},
{Header: 'day', accessor: ''}
]
<ReactTable
className="-striped -highlight"
data={this.props.items}
columns={columns}
defaultPageSize={20}/>
and i have json data like that:
"items": [
{
"day": "01",
"city": "A",
"1": "",
"2": "",
"3": "",
"4": null,
"5": "",
"6": 256,
"7": 36.07,
"8": 35.15,
"9": "",
"10": "",
"11": 6.49,
"12": 5.9,
"13": "",
"14": "",
"15": 72.0,
"16": 62.109375,
"17": 266.78,
"18": 83.59375,
"19": 444.96
},
{
"day": "02",
"city": "B",
"1": "",
"2": "",
"3": "",
"4": null,
"5": "",
"6": 234,
"7": 36.52,
"8": 35.6,
"9": "",
"10": "",
"11": 6.08,
"12": 5.71,
"13": "",
"14": "",
"15": 64.0,
"16": 43.162393162393165,
"17": 121.97,
"18": 84.1880341880342,
"19": 346.49
},
{
"day": "03",
"city": "B",
"1": "",
"2": "",
"3": "",
"4": null,
"5": "",
"6": 221,
"7": 36.96,
"8": 35.93,
"9": "",
"10": "",
"11": 5.82,
"12": 5.28,
"13": "",
"14": "",
"15": 56.99999999999999,
"16": 39.366515837104075,
"17": 94.48,
"18": 78.28054298642535,
"19": 227.4
},
]
so here is i want to make each item in items array will have column. and these columns headers will be their day property and cells will be values which in list 1, 2, 3, 5, 6. How can i do that ?
Upvotes: 1
Views: 10837
Reputation: 2606
You could just have a loop in a function to dynamically create the headers you need based on the first object of your items
list :
getColumns () {
let columns = [];
let headers = Object.keys(items[0]);
headers.forEach(header => {
columns.push({
Header: header
accessor: ""
})
}
return columns;
}
Hope it is what you were looking for (unless I didn't understand the question).
UPDATE
The first thing to do is to build the rows array to fit the way you want to display them. Indeed, the items
array should be transformed into something like this :
[{
"day01": "A",
"day02": "B",
"day03": "B"
},
{...}]
It can be done like this :
render () {
const rows = this.buildDataFromItems(items); // items is your json array
const columns = this.buildColumnsFromItems(items);
return(
<ReactTable
columns={columns}
data={rows}
/>
)
}
buildColumnsFromItems (items) {
let headers = [];
items.forEach(item => {
headers.push("day" + item.day);
})
let columns = [];
headers.forEach(header => {
columns.push({
Header: header,
accessor: header
})
});
return columns;
}
buildDataFromItems (items) {
let rows = [];
let currentHeader = "";
let currentRow = {};
for (let i = 0; i < Object.keys(items[0]).length && Object.keys(items[0])[i] !== "day"; i++) {
currentRow = {};
items.forEach(item => {
currentHeader = "day" + item.day;
currentRow[currentHeader] = item[Object.keys(items[0])[i]];
})
rows.push(currentRow);
}
return rows;
}
This piece of code should be enough to lead you to your final solution I hope :)
Upvotes: 3