Reputation: 474
I know there are different ways to check for a key inside a JSON object.
const person = {
name: 'john',
age: 25,
isTeenager: false
}
if (person.name) {
console.log('name exists')
}
if (person.hasOwnProperty('age')) {
console.log('age exists')
}
if (Object.prototype.hasOwnProperty.call(person, 'isTeenager')) {
console.log('isTeenager exists')
}
These all work fine, but which is the correct and most efficient way of doing this?
Upvotes: 0
Views: 97
Reputation: 11
Performance wise, if(obj.value != undefined)
would be the "best";
var perf = require("perf_hooks").performance;
var obj = {
iExist: "hi"
};
var start = perf.now();
if(obj.iExist != undefined) { // changed from obj.iExist to obj.iExist != undefined because of potential problems with booleans.
}
var end = perf.now();
console.log("basic if: " + (end - start));
var start1 = perf.now();
if(obj.hasOwnProperty('iExist')) {
}
var end1 = perf.now();
console.log("hasOwnProperty : " + (end1 - start));
Output:
basic if: 0.06810665130615234
hasOwnProperty : 4.006890296936035
Hope this helps!
Upvotes: 1
Reputation: 2422
You can't always rely on truthy-falsy check as you mentioned in the first example. It will fail on boolean
properties if the value is false
if (person.isTeenager) {
console.log('key exists')
}
else{
console.log('key not exists')
}
You will get falsy on this. So always use hasOwnProperty
method
Upvotes: 0
Reputation: 699
const person = {
name: 'john',
age: 25,
isTeenager: false
}
if (person.hasOwnProperty('age')) {
console.log('age exists')
}
Upvotes: 5