0

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!

2
  • 1
    Show how you're trying to export the array, that's key to the question. Commented Jun 10, 2018 at 20:07
  • try to console.log your import Commented Jun 10, 2018 at 20:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.