【问题标题】:Object to Array returns undefined对象到数组返回未定义
【发布时间】:2018-06-10 20:06:59
【问题描述】:

我正在尝试将 JS 对象转换为数组,但转换后的数组未定义。

我最初有 JSON,但根据我的阅读,它会自动解析为 JS 对象(当我尝试解析它时,我得到 SyntaxError: Unexpected token o in JSON at position 1)。另外,当我console.log(typeof cityList) 时,我得到了对象。

初始 JSON 如下所示:

    [
  {
    "id": 707860,
    "name": "Hurzuf",
    "country": "UA",
    "coord": {
      "lon": 34.283333,
      "lat": 44.549999
    }
  },
  {
    "id": 519188,
    "name": "Novinki",
    "country": "RU",
    "coord": {
      "lon": 37.666668,
      "lat": 55.683334
    }
  }
    ]

我这样导入 JSON:import cityList from './city.list.json';

我用这段代码来转换:

const cityListArray = Object.values(cityList);

如果我 console.log(cityListArray) 我得到未定义。

我也试过:const cityListArray = Object.keys(cityList).map(i => cityList[i]),但结果是一样的。

我不确定问题出在哪里。任何帮助将不胜感激!

【问题讨论】:

  • 展示你如何尝试导出数组,这是问题的关键。
  • 尝试控制台记录您的导入

标签: javascript arrays object


【解决方案1】:

您不需要转换任何内容,因为 JSON 对象已经是一个数组。

您不应该使用typeof 来检查某个东西是否是一个数组,因为它会为数组返回"object"

const a = [];
typeof a; // "object"

您应该改用Array.isArray() 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2022-01-14
    • 2020-07-20
    • 1970-01-01
    • 2021-05-20
    • 2022-01-16
    • 2016-01-30
    相关资源
    最近更新 更多