0

How to verify is set variable in object?

        <script> 
        var json;
      //json = {"one":1,"two":0}
        console.log(typeof json.one); 
        console.log("How to verify is set json?"); 
        </script>
Dmitriy
  • 37
  • 1
  • 6
  • 1
    `json && typeof json === 'object' && json.hasOwnProperty('one')` – RienNeVaPlu͢s Apr 18 '20 at 17:12
  • 1
    Does this answer your question? [How to check if object property exists with a variable holding the property name?](https://stackoverflow.com/questions/11040472/how-to-check-if-object-property-exists-with-a-variable-holding-the-property-name) – Christos Lytras Apr 18 '20 at 17:21

3 Answers3

2

if your question is if a object has certain property or not the below way works

var json = {"one":1,"two":0};
if(Object.prototype.toString.call(json) === "[object Object]" && json.hasOwnProperty('one')){
  console.log('json contains one property');
}
1
if (json && json.one) {
   console.log("It's set!");
}
Proximo
  • 6,235
  • 11
  • 49
  • 67
0

If(typeof json.one == 'undefined")