Reputation: 18805
Is there any method to return a bool for this example instead of one of the operands?
var json = {"test":"asd", "example":"fgh"};
var exists = json.test && json.example;
console.log(exists); // returns 'fgh'
console.log(json.test && json.example); // returns 'fgh'
To achieve the equivalent of:
var json = {"test":"asd", "example":"fgh"};
var exists= json.hasOwnProperty("test") && json.hasOwnProperty("example");
console.log(exists); // returns true
Upvotes: 0
Views: 68
Reputation: 10390
Simplest thing I can think of is:
var json = {"test":"asd", "example":"fgh"};
var exists = json.test && json.example;
console.log(Boolean(exists));
returns true
Upvotes: 1
Reputation: 6824
This is how you convert a non-boolean value to a boolean
var json = {"test":"asd", "example": "fgh"};
var exists = !!(json.test && json.example); // converts to boolean
console.log(exists); // returns a boolean value
Upvotes: 2