【问题标题】:How to get first array in fetch promise如何在获取承诺中获得第一个数组
【发布时间】:2019-09-11 09:09:14
【问题描述】:

我需要在我的 fetch promise 中返回一个包含我所有数据的 JSON 对象。问题是我不知道对象名称是什么。我所知道的是,总会有一个对象。

这是我的示例代码,我在其中得到了我需要知道对象名称的内容(在本例中为 foo

  return fetch(endPoint)
    .then(res => res.json())
    .then(res => res.foo)
    .then(res => console.log(res))

我的回复是这样的

{
    "foo": [
        "bar1",
        "bar2",
        "bar3"
    ]
}

但是,如果这是响应,我的代码将失败:

{
    "goo": [
        "bar1",
        "bar2",
        "bar3"
    ]
}

无论调用什么对象,我如何确保我的代码始终有效?

【问题讨论】:

    标签: javascript arrays json object ecmascript-6


    【解决方案1】:

    您可以使用Object.values() 并访问其第一个元素。

    const obj = {"foo": ["bar1","bar2", "bar3"]}
    const res = Object.values(obj)[0]
    console.log(res)

    您可以使用Array Destructuring 使其更短

    const obj = {"foo": ["bar1","bar2", "bar3"]}
    const [res] = Object.values(obj)
    console.log(res)

    【讨论】:

      【解决方案2】:

      使用Object.values:

      const obj = {
        "foo": [
          "bar1",
          "bar2",
          "bar3"
        ]
      };
      
      const [foo] = Object.values(obj);
      console.log(foo);

      上面使用destructuring,它是这个的简写:

      const foo = Object.values(obj)[0];
      

      旧语法:

      var obj = {
          "foo": [
              "bar1",
              "bar2",
              "bar3"
          ]
      };
      
      var foo = obj[Object.keys(obj)[0]];
      console.log(foo);

      【讨论】:

      • 你也可以进一步解释,你在那里做了什么,也许 OP 不明白什么是解构。 (不是反对者)
      • 哦,哎呀,我的坏@MaheerAli,我会解决这个问题的。
      • 现在修复了@MaheerAli,好点了吗?
      猜你喜欢
      • 2017-02-17
      • 2019-10-04
      • 2017-05-29
      • 2019-01-28
      • 1970-01-01
      • 2021-08-12
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多