Showing posts with label Object.keys(). Show all posts
Showing posts with label Object.keys(). Show all posts

Friday, August 25, 2017

Javascript Object properties

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
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top