Wednesday, December 13, 2017

How to check object property in Node.js

Here's the way...


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var my_obj = {
    name : "Hisoka",
    skills: "Bungejigum"
};

if(my_obj.hasOwnProperty('status')) {
    console.log(" my object has status property");
} else {
    console.log(" status is NOT in there");
}

if(my_obj.hasOwnProperty('skills')) {
    console.log(" my object has skills property");
} else {
    console.log(" skills is NOT in there");
}

/**
* Another way for checking property is using 'in'.
* but BE CAREFUL! The in operator matches all object keys,
* including those in the object's prototype chain.
* So it's preferred to use hasOwnProperty
*/
console.log("\n");
if('status' in my_obj) {
    console.log(" status is in there");
} else {
    console.log(" status is NOT in there");
}


if('skills' in my_obj) {
    console.log(" skills is in there");
} else {
    console.log(" skills is NOT in there");
}

Result :

No comments:

Post a Comment