0

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');
              }
          });
Dexygen
  • 12,287
  • 13
  • 80
  • 147
Nag
  • 806
  • 1
  • 13
  • 28
  • What precisely is the problem? – lonesomeday Feb 03 '17 at 18:11
  • parse `json` to javascript object then `hasOwnProperty ` will work. `var res = JSON.parse(person);` – Ashot Feb 03 '17 at 18:12
  • 1
    Possible duplicate of [Convert JavaScript string in dot notation into an object reference](http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference) – Heretic Monkey Feb 03 '17 at 18:25

1 Answers1

1

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.
Dexygen
  • 12,287
  • 13
  • 80
  • 147