Detecting Properties
The in
operator looks for a property with a given name in a specific object and returns true if it finds it.
console.log("name" in person1); // true
console.log("age" in person1); // true
console.log("title" in person1); // false
Keep in mind that methods are just properties that reference functions, so you can check for the existence of a method in the same way.
const person1 = {
name: "Nicholas",
sayName: function() {
console.log(this.name);
}
};
console.log("sayName" in person1); // true
In some cases, however, you might want to check for the existence of a property only if it is an own property. The in
operator checks for both own properties and prototype properties, so you’ll need to take a different approach. Enter the hasOwnProperty()
method, which is present on all objects and returns true
only if the given property exists and is an own property.
const person1 = {
name: "Nicholas",
sayName: function() {
console.log(this.name);
}
};
console.log("name" in person1); // true
console.log(person1.hasOwnProperty("name")); // true
console.log("toString" in person1); // true
console.log(person1.hasOwnProperty("toString")); // false
Removing Properties
You need to use the delete
operator to completely remove a property from an object.
const person1 = {
name: "Nicholas"
};
console.log("name" in person1); // true
delete person1.name; // true - not output
console.log("name" in person1); // false
console.log(person1.name); // undefined
Enumeration
By default, all properties that you add to an object are enumerable, which means that you can iterate over them using a for-in loop. This example uses bracket notation to retrieve the value of the object property and output it to the console, which is one of the primary use cases for bracket notation in JavaScript.
var property;
for (property in object) {
console.log("Name: " + property);
console.log("Value: " + object[property]);
}
If you just need a list of an object’s properties, use Object.keys()
method to retrieve an array of enumerable property names. Typically, you would use Object.keys()
in situations where you want to operate on an array of property names and for-in when you don’t need an array.
var properties = Object.keys(object);
// if you want to mimic for-in behavior
var i, len;
for (i=0, len=properties.length; i < len; i++){
console.log("Name: " + properties[i]);
console.log("Value: " + object[properties[i]]);
}
Keep in mind that not all properties are enumerable. You can check whether a property is enumerable by using the propertyIsEnumerable()
method, which is present on every object:
var person1 = {
name: "Nicholas"
};
console.log("name" in person1); // true
console.log(person1.propertyIsEnumerable("name")); // true
var properties = Object.keys(person1);
console.log("length" in properties); // true
console.log(properties.propertyIsEnumerable("length")); // false
0 comments:
Post a Comment