Is there a way I can easily map an array of rows to a table in reactjs/javascript? My data looks like this:
rows: [
['10kg', '12.5', '1.25', '8'],
['25kg', '28.75', '1.15', '6'],
['50kg', '50', '1.0', '5'],
['100kg', '100', '1.0', '3'],
['250kg', '250', '1.0', '5'],
['500kg', '500', '1.0', '5'],
['1liter', '1000', '1.0', '5']
]
"labels": [
"Weight",
"Price",
"Price Per",
"Amount"
],
In python there are tables where I can set the columns then loop through the array and add the row through the array item. Is there something like this for javascript/reactjs?
CodePudding user response:
Change the data as list to objects:
let rows = [['10kg', '12.5', '1.25', '8'],
['25kg', '28.75', '1.15', '6'],
['50kg', '50', '1.0', '5'],
['100kg', '100', '1.0', '3'],
['250kg', '250', '1.0', '5'],
['500kg', '500', '1.0', '5'],
['1liter', '1000', '1.0', '5']];
let labels = ["Weight","Price","Price Per","Amount"];
let values = rows.map(row => {
let d = {};
row.forEach((c, i) => d[labels[i]] = c);
return d;
});
console.log(values)
let columns = labels.map(l => ({field: l, width: 150}));
console.log(columns);
Then render with a DataGrid
return <DataGrid rows={values} columns={columns}/>