数组对象返回未定义 [英] Object to Array returns undefined

查看:57
本文介绍了数组对象返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

初始JSON如下所示:

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
    }
  }
    ]

我这样导入JSON:从"./city.list.json"导入cityList;

I import JSON like this: import cityList from './city.list.json';

我使用以下代码进行转换:

I use this code to convert:

const cityListArray = Object.values(cityList);

如果我 console.log(cityListArray)我不确定.

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

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!

推荐答案

您无需转换任何内容,因为JSON对象已经是数组.

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

您不应该检查某物是否是具有 typeof 的数组,因为它会为数组返回"object" .

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

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

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

这篇关于数组对象返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆