开发者问题收集

TypeError:无法将未定义或无效转换为对象JavaScript

2020-10-12
398

我的 JSON 出现一个类型错误, 我正在基于 json 构建树,我的 JSON 结构中不是静态字段,键值是动态的,

当我有 JSON 数据时 -

const data = [
  
  {
    "class": "abc",
    magList: "",
    authKeyMgmtMode: {
      "class": "OctetString",
      octets: "00"
    },
    wsEnable: true,
    wlans: true,
    wsle: true,
    busey: "567ff7c5[180188_180188,temp-ssid_Global_NF_e06779e9]",
    sspe: 0
  }
];

下面是沙盒,运行正常 - 代码沙盒 - https://codesandbox.io/s/flamboyant-blackwell-dw5yn?file=/index.js

当我再添加一个值时

Ipv6Name: null,

在 json 数组中,它给出了错误,

错误 - 无法将未定义或 null 转换为对象

Object.keys(object).map((key, reactKey) => {

我有检查了参考资料中是否有相同的错误,但无法继续。 请指导我。

已编辑 -

I noticed I was sending null to Object.keys but I was doing check in isPrimative function I was using the check but there were typo and few logical mistake, I was checking typeof value === null , Thanks for pointing out...

1个回答

使用此代码,因为 null 的类型是 object :

isPrimative = (value) => {
    return (
      typeof value === "string" ||
      typeof value === "" ||
      typeof value === "number" ||
      typeof value === "boolean" ||
      value === null
    );
  };
Iosif
2020-10-12