zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JS中判断JSON数据是否存在某字段的方法

JS方法数据JSONJSON 判断 是否 存在
2023-06-13 09:15:19 时间

如何判断传过来的JSON数据中,某个字段是否存在,

1.obj["key"]!=undefined
这种有缺陷,如果这个key定义了,并且就是很2的赋值为undefined,那么这句就会出问题了。
2.!("key"inobj)
3.obj.hasOwnProperty("key")

这两种方法就比较好了,推荐使用。

答案原文:

Actually,checkingforundefined-nessisnotanaccuratewayoftestingwhetherakeyexists.Whatifthekeyexistsbutthevalueisactuallyundefined?

varobj={key:undefined};
obj["key"]!=undefined//false,butthekeyexists!

Youshouldinsteadusetheinoperator:

"key"inobj//true,regardlessoftheactualvalue

Ifyouwanttocheckifakeydoesn"texist,remembertouseparenthesis:

!("key"inobj)//trueif"key"doesn"texistinobject
!"key"inobj//ERROR!Equivalentto"falseinobj"

Or,ifyouwanttoparticularlytestforpropertiesoftheobjectinstance(andnotinheritedproperties),usehasOwnProperty:

obj.hasOwnProperty("key")//true

PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线json压缩/转义工具: