javascript - 如何使用switch语句查找json对象中是否存在键值对
问题描述
json type :1
var x={
"address": {
"county": "abc",
"state_district": "asd",
"state": "test",
"country": "test1",
"country_code": "test"
}
}
Type:2
var x ={ "address": {
"suburb": "",
"city_district": "",
"city": "",
"county": "",
"state": "",
"postcode": "",
"country": "",
}}
type:3
var x= {"address": {
"amenity": "",
"road": "",
"town": "",
"county": "",
"state_district": "",
"state": "",
"postcode": "",
"country": "",
"country_code": ""
}
}
switch(x.address)
{
case 'city':
return x.address.city;
break;
case 'village':
return x.address.village;
break;
default:
alert('err');}
这是我的 JSON 内容。 address
属性将具有一些额外的键值,具体取决于位置,如city
、village
、suburb
等。
我需要使用 switch 语句检查特定键是否存在。上面显示了带有附加属性的示例 JSON。
解决方案
您也许可以使用Object.prototype.hasOwnProperty()
if(x.address.hasOwnProperty('city')){
return x.address.city
}else if(x.address.hasOwnProperty('village')){
return(x.address.village)
}else{
alert('err')
}
See https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/hasOwnProperty
推荐阅读
- google-vault-api - Google Vault Export API 不适用于云存储 API
- javascript - Angular 6 树图
- atomikos - 如何向 Atomikos TransactionStateHandler 添加同步
- hibernate - spring boot 和 hibernate 5 - EntityManagerFactory 会话管理
- c# - C#动态构建匿名对象
- docker - 使用 docker 将 mule 应用程序部署到 mule 集群
- python - 如何将具有两个以上值的 TensorFlow 数据集提供给 Keras
- acumatica - 如何在现有销售订单屏幕的新自定义选项卡中获取拆分容器
- python - 停止烧瓶复制加载的变量
- c# - 只执行程序的一部分