如何在JavaScript中通过API调用创建一个新对象



我试图从从API检索的数据创建一个新对象。我修改了我的代码一点,并从端点复制了数据,但它将使用fetch调用。以下是目前为止的内容:

const urls = [//array of urls]


const fetchData = async() => {
try {
const response = await Promise.all(
urls.map(url => fetch(url).then(res => res.json()))
)
console.log(response)
if (urls.transfers.status !== 'failed') {
return {
originUserName: urls.users.firstName + data.users.lastName,
targetUserName: urls.targetAccount + urls.users.firstName + urls.users.lastName,
amount: urls.transfers.amount,
description: urls.transfers.description,
likesCount: urls.users.likes
};
}
} catch (error) {
console.log("Error", error)
}
}

我一直在我的代码中获得状态未定义错误。我通过对象数组进行映射,但它看起来好像没有抓取任何键。

也没有定义用户。你可以试试:

const users =[{
"id": 1,
"user": 2,
"transfer": 1
},

数据无效。我已经修改了你的数据结构,它应该看起来像这样:

const data = [
[{
id: 1,
status: "complete",
originAccount: 1,
targetAccount: 4,
amount: 10000,
description: "Consider us even >:|",
initiatedAt: "2019-05-20T12:53:38-04:00",
completedAt: "2019-05-22T12:00:00-04:00",
failedAt: null,
},
{
id: 2,
status: "initiated",
originAccount: 1,
targetAccount: 7,
amount: 5500,
description: "Winner, winner...",
initiatedAt: "2019-05-23T12:53:38-04:00",
completedAt: null,
failedAt: null,
},
{
id: 3,
status: "complete",
originAccount: 2,
targetAccount: 5,
amount: 2500,
description: "Thanks for the cut!!",
initiatedAt: "2019-05-04T12:53:38-04:00",
completedAt: "2019-05-06T12:00:00-04:00",
failedAt: null,
},
{
id: 4,
status: "complete",
originAccount: 7,
targetAccount: 5,
amount: 1000,
description: "Splitting the cab",
initiatedAt: "2019-05-10T12:53:38-04:00",
completedAt: "2019-05-12T12:00:00-04:00",
failedAt: null,
},
{
id: 5,
status: "failed",
originAccount: 4,
targetAccount: 3,
amount: 1257,
description: "Drinks :cocktail:",
initiatedAt: "2019-02-10T12:53:38-04:00",
completedAt: null,
failedAt: "2019-02-11T12:00:00-04:00",
},
],
[
({
id: 1,
user: 2,
transfer: 1,
}, {
id: 2,
user: 4,
transfer: 1,
}, {
id: 3,
user: 4,
transfer: 3,
}, {
id: 4,
user: 1,
transfer: 4,
}),
],
[
({
id: 1,
firstName: "Aaron",
lastName: "Howard",
accounts: [1, 2],
transfers: [1, 2, 3],
likes: [4],
}, {
id: 2,
firstName: "Cassie",
lastName: "Perez",
accounts: [3],
transfers: [5],
likes: [1],
}, {
id: 3,
firstName: "Larry",
lastName: "Smith",
accounts: [4],
transfers: [1, 5],
likes: [],
}, {
id: 4,
firstName: "Jean",
lastName: "Sawyer",
accounts: [5, 6],
transfers: [3, 4],
likes: [],
}, {
id: 5,
firstName: "Julie",
lastName: "Nimmo",
accounts: [7],
transfers: [2, 4],
likes: [],
}),
],
];
//Extract transfers only
const transfers = data.map(d => d)[0];
//Now check status of each transfer
transfers.map((transfer) => {
if (transfer.status !== 'failed') {
//...your logic
}
})

  • 首先,我只是想指出数组分配给
  • 第二,如果你接收的数据确实是那个数组,那么我看到所有的键名称"transfer "是一个数字数组。所以错误是有意义的。
  • 而不是在Promise之后添加控制台日志。我宁愿在Promise.all中添加第二个控制台日志。如果你能粘贴到这里,这将有助于我们提供更好的解决方案。

最新更新