Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  198] [ 5]  / answers: 1 / hits: 93156  / 8 Years ago, wed, august 24, 2016, 12:00:00

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.


More From » jquery

 Answers
32



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)




[#60924] Tuesday, August 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorw

Total Points: 484
Total Questions: 120
Total Answers: 107

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;