【问题标题】:How to create a new object from an API call in JavaScript如何从 JavaScript 中的 API 调用创建新对象
【发布时间】:2021-09-05 19:56:09
【问题描述】:

我正在尝试根据从 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)
  }
}

我的代码中不断出现未定义状态错误。我映射了对象数组,但它看起来好像没有抓住任何键。

【问题讨论】:

  • 为什么要定义data.transfers.status?您的数据结构无效。顶层是一个数组!!所以不能有一个名为transfers 的属性,并且没有一个名为transfers 的属性是对象。
  • 你的 JS data 无效 => } [{
  • 我试图获取状态属性并检查它是否没有失败。如果是这样,我将返回一个新的对象数组

标签: javascript json api object


【解决方案1】:

您还没有定义用户。 你可以试试这个:

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

【讨论】:

    【解决方案2】:

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

    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
      }
    })

    【讨论】:

    • transfers.status 返回一个未定义的错误并且用户或喜欢相同。遍历所有内容的唯一方法是通过对象表示法,例如 transfer[0]['status'] 。有没有更简单的方法来获取数据,而不必指定你想要的数组?
    • 这是 transfer.status 不是 transfer.status
    • transfer.status 也返回未定义传输
    【解决方案3】:
    • 首先,我只想指出分配给的数组 数据无效。
    • 其次,如果您收到的数据确实是那个数组,那么我看到所有名为“transfers”的键都是数字数组。所以这个错误是有道理的。
    • 与其在 Promise.all 之后添加控制台日志,我宁愿通过在 Promise.all 中添加第二个然后添加控制台日志来添加控制台日志。如果您可以这样做并将其粘贴到此处,那将有助于我们提供更好的解决方案。

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    • 它应该是 3 个独立的对象数组。转移,喜欢,用户。我在 Promise.all 中添加了 then 语句,得到了引用错误 Error ReferenceError: Cannot access 'response' before initialization
    猜你喜欢
    • 2017-06-14
    • 2015-09-24
    • 2021-12-28
    • 2015-10-06
    • 2011-08-15
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多