首页 > 解决方案 > 如何使用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属性将具有一些额外的键值,具体取决于位置,如cityvillagesuburb等。

我需要使用 switch 语句检查特定键是否存在。上面显示了带有附加属性的示例 JSON。

标签: javascriptjsonswitch-statement

解决方案


您也许可以使用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

推荐阅读