简体   繁体   English

数组对象返回未定义

[英]Object to Array returns undefined

Im trying to convert JS Object to an Array but Array after conversion is undefined. 我试图将JS对象转换为数组,但转换后的数组未定义。

I initially have JSON but from what I have read it is automatically parsed into JS Object (when I try to parse it, I get SyntaxError: Unexpected token o in JSON at position 1). 我最初有JSON,但是根据我的阅读,它会自动解析为JS Object(当我尝试解析它时,我会在位置1的JSON中收到SyntaxError:Unexpected token o)。 Also when I console.log(typeof cityList) I get Object. 另外,当我console.log(typeof cityList)我得到对象。

Initial JSON goes like this: 初始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
    }
  }
    ]

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

I use this code to convert: 我使用以下代码进行转换:

const cityListArray = Object.values(cityList);

If I console.log(cityListArray) I get undefined. 如果我console.log(cityListArray)我不确定。

I also tried: const cityListArray = Object.keys(cityList).map(i => cityList[i]) but result is the same. 我也尝试过: const cityListArray = Object.keys(cityList).map(i => cityList[i])但结果是相同的。

Im not sure where the problem is. 我不确定问题出在哪里。 Any help would be appreciated! 任何帮助,将不胜感激!

You don't need to convert anything, since the JSON object is already an array. 您不需要转换任何内容,因为JSON对象已经是一个数组。

You shouldn't check if something is an array with typeof since it returns "object" for arrays. 您不应该检查某物是否为typeof数组,因为它会为数组返回"object"

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

You should use the Array.isArray() method instead. 您应该改用Array.isArray()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM