javascript - javascript中如何将多个对象转换为键值对的Array[]

标签 javascript react-native

我正在尝试在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/

相关文章:

javascript - 如何在 Sequelize 中创建关联

javascript - 我编辑 AppDelegate.m 来监听端口 8080 但它仍然失败,因为 8081 正在使用中

java - bindservice 不会启动服务并且 onserviceconnect 不会调用

react-native - 将本地镜像处理到应用程序中 - 出现 sha1 错误

javascript - 如何在 Node js中的同一模块文件中使用模块

javascript - jQuery $.post 和 $.ajax POST 请求不适用于 Express 中的 app.post() 方法

amazon-web-services - 从 React-Native 调用 AWS Lambda 函数

ios - 对 [AppName] 进行 native 签名测试需要开发团队 ios

javascript - 如何防止禁用 javascript 的用户提交表单?

javascript - 当循环遍历 JS 数组的值并删除值时,是否需要使用 while 而不是 for?