User97798 User97798 - 3 months ago 8
Javascript Question

How to check key exist in json or not

I have JSON object and i want to check key is set in that JSON object

Here is JSON object

var Data_Array = {
"Private": {
"Price": {
"Adult": "18",
"Child": [{
"FromAge": "0",
"ToAge": "12",
"Price": "10"
}]
}
}
}


If JSON Object like this as you can see Child is not exist, then how to check this

var Data_Array = {
"Private": {
"Price": {
"Adult": "18"
}
}
}


I have tried

if(Data_Array.Private.Price.Child[0].Price != "undefined"){
...
}


But it is showing me this error


Uncaught TypeError: Cannot read property


I am not be able to find out what should i do.

Answer

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

for child key

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

create variable child

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)

if there is no child

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)

Comments