DekGenius.com
JAVASCRIPT
How to tell if an attribute exists on an object
const user = {
name: "Sicrano",
age: 14
}
user.hasOwnProperty('name'); // Retorna true
user.hasOwnProperty('age'); // Retorna true
user.hasOwnProperty('gender'); // Retorna false
user.hasOwnProperty('address'); // Retorna false
how to check wether the property exist in a object in java script
if (obj.hasOwnProperty('prop')) {
// do something
}
test if property exists javascript
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
check if js property exists in class
myObj.hasOwnProperty(myProp)
Check object property exists or not in js
const user1 = {
username: "john"
};
const user2 = {
username: "duo"
authority: "grepper"
}
// check object property
console.log(user1.hasOwnProperty('authority')); // false
console.log(user2.hasOwnProperty('authority')); // true
check property exists
let person = {
firstName: 'John',
lastName: 'Doe'
};
let result = 'firstName' in person;
console.log(result); // true
result = 'age' in person;
console.log(result); // false
Code language: JavaScript (javascript)
JavaScript check if property exists in Object
const userOne = {
name: 'Chris Bongers',
email: 'info@daily-dev-tips.com',
};
const userTwo = {
name: 'John Do',
};
console.log(userOne.hasOwnProperty('email'));
// Returns: true
console.log(userTwo.hasOwnProperty('email'));
// Returns: false
check property exists
let result = person.hasOwnProperty('firstName');
console.log(result); // true
Code language: JavaScript (javascript)
check if property exists javascript
// the coolest way
const obj = {
weather: 'Sunny;
}
if('weather' in obj) {
// do something
}
check property exists in object javascript
const employee = {
id: 1,
name: "Jhon",
salary: 5000
};
const isSalaryExist = "salary" in employee;
console.log(isSalaryExist); //true
const isGenderExist = "gender" in employee;
console.log(isGenderExist); //false
check property exists
let person = {
firstName: 'John',
lastName: 'Doe',
age: undefined
};
let result = person.age !== undefined;
console.log(result); // false
Code language: JavaScript (javascript)
© 2022 Copyright:
DekGenius.com