Reputation: 3
I'm trying to display a table in react-native but it requires the data to be in arrays,
the API returns an object with all the rows, so far I have managed to convert only if there is a single row and doesn't convert the second row if its available.
Api from the server
0: {title: "Transportation", amount: "100"}
1: {title: "Food", amount: "50"}
what I need is
0:["Transportation", "100"]
1:["Food", "50"]
this is my code
const state = this.state;
let table = this.state.payments;
console.log(table);
const tableD = Object.keys(table[0]).map((key, index) => table[0][key]);
console.log(tableD);
const tableData = [tableD];
console.log(tableData);
return (
<Table borderStyle={{borderWidth: 2, borderColor: theme.colors.primary}}>
<Row data={state.tableHead} style={{ height: 40, backgroundColor: theme.colors.gray2}} textStyle={{margin: 6}}/>
<Rows data={tableData} textStyle={{ margin: 6, }}/>
</Table>
)
this is the error that I get
Invariant Violation: Objects are not valid as a React child (found: object with keys {title, amount}). If you meant to render a collection of children, use an array instead.
What could I be doing wrong?
Upvotes: 0
Views: 1709
Reputation: 4489
That's because you are telling it to change just the first (index 0) value in the array.
First of all, you need to use Object.values as said by matevzpoljianc, after that you need to loop trough all your array.
So it would be:
let table = this.state.payments;
const tableD = this.state.payments.map(item=>Object.values(item))
console.log(tableD);
Now you would've your array of arrays.
EDIT.
If you server is responding with an object that has numbers as keys then what I've wrote won't work, but you can simply hotfix it to:
let table = this.state.payments;
const tableD = Object.values(this.state.payments).map(item=>Object.values(item))
console.log(tableD);
Upvotes: 1
Reputation: 275
It's quite simple, here's how:
let table = this.state.payments.slice(); //use .slice() to create a copy.
for(row in table){
table[row] = Object.values(table[row]); //direct transformation
}
console.log(table); //table is your formatted table.
Upvotes: 0
Reputation: 211
Use Object.values(obj) function to get just values.
If you need key, value pairs you can use Object.entries(obj)
Upvotes: 0