Object to Array returns undefined

五迷三道 提交于 2021-02-11 14:46:27

问题


Im trying to convert JS Object to an Array but Array after conversion is undefined.

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). Also when I console.log(typeof cityList) I get Object.

Initial JSON goes like this:

    [
  {
    "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';

I use this code to convert:

const cityListArray = Object.values(cityList);

If I console.log(cityListArray) I get undefined.

I also tried: const cityListArray = Object.keys(cityList).map(i => cityList[i]) but result is the same.

Im not sure where the problem is. Any help would be appreciated!


回答1:


You don't need to convert anything, since the JSON object is already an array.

You shouldn't check if something is an array with typeof since it returns "object" for arrays.

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

You should use the Array.isArray() method instead.



来源:https://stackoverflow.com/questions/50787605/object-to-array-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!