Use*_*798 7 javascript jquery json
我有JSON对象,我想检查在该JSON对象中设置的键
这是JSON对象
var Data_Array = {
"Private": {
"Price": {
"Adult": "18",
"Child": [{
"FromAge": "0",
"ToAge": "12",
"Price": "10"
}]
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果JSON Object像这样你可以看到Child不存在,那么如何检查这个
var Data_Array = {
"Private": {
"Price": {
"Adult": "18"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试过了
if(Data_Array.Private.Price.Child[0].Price != "undefined"){
...
}
Run Code Online (Sandbox Code Playgroud)
但它告诉我这个错误
未捕获的TypeError:无法读取属性
我无法知道我该怎么做.
小智 15
var json = {key1: 'value1', key2: 'value2'}
"key1" in json ? console.log('key exists') : console.log('unknown key')
"key3" in json ? console.log('key exists') : console.log('unknown key')Run Code Online (Sandbox Code Playgroud)
对于儿童钥匙
var Data_Array = {
"Private": {
"Price": {
"Adult": "18",
"Child": [{
"FromAge": "0",
"ToAge": "12",
"Price": "10"
}]
}
}
}
'Child' in Data_Array.Private.Price ? console.log('Child detected') : console.log('Child missing')Run Code Online (Sandbox Code Playgroud)
创建变量子
var Data_Array = {
"Private": {
"Price": {
"Adult": "18",
"Child": [{
"FromAge": "0",
"ToAge": "12",
"Price": "10"
}]
}
}
}
var child = 'Child' in Data_Array.Private.Price && Data_Array.Private.Price.Child[0] || 'there is no child'
console.log(child)Run Code Online (Sandbox Code Playgroud)
如果没有孩子
var Data_Array = {
"Private": {
"Price": {
"Adult": "18"
}
}
}
var child = 'Child' in Data_Array.Private.Price && Data_Array.Private.Price.Child[0] || 'there is no child'
console.log(child)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45770 次 |
| 最近记录: |