问题
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