我正在尝试在react-native中显示表格,但它要求数据位于数组中,
API 返回一个包含所有行的对象,到目前为止,我已经设法仅在存在单行时进行转换,并且不会转换第二行(如果可用)。
来自服务器的API
0: {title: "Transportation", amount: "100"}
1: {title: "Food", amount: "50"}
我需要的是
0:["Transportation", "100"]
1:["Food", "50"]
这是我的代码
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>
)
这是我收到的错误
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.
我可能做错了什么?
最佳答案
这是因为您告诉它仅更改数组中的第一个(索引 0)值。
首先,您需要按照matevzpoljianc所述使用Object.values,之后您需要循环遍历所有数组。
所以会是:
let table = this.state.payments;
const tableD = this.state.payments.map(item=>Object.values(item))
console.log(tableD);
现在你就拥有了数组的数组。
编辑。
如果您的服务器使用以数字为键的对象进行响应,那么我编写的内容将不起作用,但您可以简单地将其修复为:
let table = this.state.payments;
const tableD = Object.values(this.state.payments).map(item=>Object.values(item))
console.log(tableD);
关于javascript - javascript中如何将多个对象转换为键值对的Array[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57691705/