check if in object javascript code example
Example 1: check the properties of an object in javascript
for (var name in object) {
if (object.hasOwnProperty(name)) {
}
}
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name');
hero.hasOwnProperty('realName');
Example 2: test if property exists javascript
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name');
hero.hasOwnProperty('realName');
Example 3: check if object has method javascript
if(typeof myObj.prop2 === 'function') {
alert("It's a function");
} else if (typeof myObj.prop2 === 'undefined') {
alert("It's undefined");
} else {
alert("It's neither undefined nor a function. It's a " + typeof myObj.prop2);
}
Example 4: javascript check if is object
obj = {
"data": 123
}
arr = [
"data",
123
]
function obj_or_arr(val) {
if (typeof val === "object") {
try {
for(x of val)
break;
return "array";
} catch {
return "object";
}
} else return false;
}
console.log(obj_or_arr(obj))
console.log(obj_or_arr(arr))
console.log(obj_or_arr(123))
console.log(obj_or_arr("hello world"))
console.log(obj_or_arr(true))
console.log(obj_or_arr(false))
Example 5: javascript check if object
typeof yourVariable === 'object'
typeof yourVariable === 'object' && yourVariable !== null
Example 6: checking a condition in object javascript
{ id: 'some-id', ...(true && { optionalField: 'something'})}