Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

javascript - how to find if key value pair exists in json object using switch statement

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');}

This my JSON content. address property will have some additional key values depending on locality like city, village, suburb, etc.

I need to check if a particular key is present or not using switch statement. Sample JSON with additional property are shown above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In addition to the answer from Fiouze, you can also do these:

// will return true if the property exists.
'city' in x.address

// will return a value if set or undefined if not.
x.address.city

But if you want to stick with the switch case, you can iterate through the properties by doing something like:

for (const prop in x.address) {
  switch (prop) {
    case 'city': 
      return x.address.city;
    case 'village':
      return x.address.village;
    default:
      alert('err');
  }
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...