javascript - 如何检查我的 JSON 字段是否已定义?

标签 javascript arrays node.js json typescript

我正在解析 JSON 并尝试访问它的一个字段,它是一个数组。

const myObj: MyObj = JSON.parse(myJson);
console.log(myObj.myArray); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray == 'undefined'); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray.length); //TypeError: Cannot read property 'length' of undefined
console.log(myObj.myArray !== null); //true

我可以毫无问题地遍历我的数组并对数据执行我需要的操作。但我需要检查以确保 myArray 字段在迭代时有效。当我尝试执行此操作时,出现如上所示的错误。

我非常非常困惑。谁能向我解释一下发生了什么事以及如何解决它?

最佳答案

使用 in 时要小心,因为它会搜索整个原型(prototype)链。

const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);

console.log('constructor' in myObj); // true (BAD)

相反,尝试使用 .hasOwnProperty(),如下所示:

const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);

console.log(myObj.hasOwnProperty("a")); // true
console.log(myObj.hasOwnProperty("constructor")); // false

关于javascript - 如何检查我的 JSON 字段是否已定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141364/

相关文章:

javascript - 在 angularjs 服务中缓存数组

c++ - 让用户指定数组大小在 XCode 中有效,但在 Visual Studio 中无效

java - 对 HashMap 在底层如何工作感到困惑

c# - 系统.UnauthorizedAccessException : Creating an instance of the COM component fails with error 80070005 (C#)

javascript - 删除请求未持久保存在 Node js 中

node.js - 运行时无法旁加载 Office 加载项 'npm start'

javascript - CSS视差标题和粘性导航相互排斥?

javascript - 无法理解 meteor 特定语法

javascript - 关于 JavaScript 基础的几个问题 - $, "is not a function"

arrays - 对 3 维数组进行子集化时不要删除维度