Reputation: 956
I want to know if the key-value pair exists in JSON data while retrieving data. Display "NA" inside div element if not present or else display the value of that key.
HTML:
<div id="output"></div>
jQuery:
$.get('http://api.fixer.io/2000-02-03',function(person){
if(person.hasOwnProperty('rates.BGN')) {
$('#output').text(person.rates.BGN);
}
else {
$('#output').text('NA');
}
});
Upvotes: 0
Views: 704
Reputation: 12561
First, you need to parse person into JSON.
Secondly you are misusing hasOwnProperty, it cannot be used to drill down into an object more than one level the way you are trying.
Finally hasOwnProperty is just unnecessary -- just test for existence as follows:
$.get('http://api.fixer.io/2000-02-03',function(person){
person = JSON.parse(person);
if(person.rates.BGN !== undefined) {
$('#output').text(person.rates.BGN);
}
//etc.
Upvotes: 1