3 JavaScript Object Access Hacks You Need to Know

Javascript

We have three different ways to access properties in Javascript Objects, all are very useful and can be combined with each other. The methods are:

  • Use the assessor . with the property: object.property
  • Use the property name within brackets, object['property']
  • Using Object destructuring const { property } = object

Let’s see how each syntax works to access properties in objects. And understand when it is reasonable, depending on the situation, to use one way or another.

Creating Objects in Javascript

Before we understand how to access the properties in objects, let’s see how we can create these objects.

Objects in Javascript are sets of key-values that, unlike arrays, have no defined order.

//{key : value}
{userName: "@EverythingDebug" }

The simplest and most efficient way to create a Javascript Object is using the literal object form with {}. You simply need to create a variable, in the example below I called the variable myProfile, and pass the key-value properties to this variable, very simple.

const myProfile = {
        title: "@EverythingDebug",
        url: "https://twitter.com/EverythingDebug",
        tweets: 9,
        followers: 4,
        following: 6
      };

How to access properties in Javascript Objects

Let’s list here the three methods you can use to access properties in objects, each one with its own utility. Each method may fit better, depending on the situation or what the project requires.

Method 1: Dot property accessor

This first method is likely, the most common way to access properties in Javascript Objects. Java also uses this same format to access properties in objects.

In Javascript this is the syntax you will use:

expression.identifier

expression must be associated with an object, and identifier is the name of the property you would like to access.

For example, for our myProfile object, let’s try to access the title and tweets properties.

const myProfile = {
        title: "@EverythingDebug",
        url: "https://twitter.com/EverythingDebug",
        tweets: 9,
        followers: 4,
        following: 6
      };
console.log(myProfile.title); // @EverythingDebug
console.log(myProfile.tweets); // 9

myProfile.title is a dot property assessor that reads the property name of the myProfile object.

You can use the dot property assessor in a chain to access deeper properties of an object: object.prop1.prop2. You can learn more about this on this post where I talk about 3 Powerful Ways to Access Properties in Javascript Objects.

Choose this method when the name of the property is known in advance.

Considerations about the method

This assessor works very well to access properties in Javascript Objects only when the identifiers (keys) are valid.

Valid identifiers:

Um identificador válido em JavaScript pode conter letras no formato Unicode, $, _, e dígitos 0…9.

A valid JavaScript identifier may contain letters in Unicode format, $, _, and digits 0…9.

{
   "title": "Debug",
   "$title": "Debug",
   "_title": "Debug",
   "title9": "Debug",
}

Invalid identifiers:

If you want to use this method to access properties in Javascript Objects, Javascript will not allow you to use some characters in the object properties. Like dot ., hyphen - or if it starts with a number.

{
   "title.name": "Debug",
   "title-name": "Debug",
   "5title": "Debug",
}

Let’s run the examples above and see what results we get using each of them:

const myObject = {
   "title": "Debug",
   "$title": "Debug",
   "_title": "Debug",
   "title9": "Debug",
   "title.name": "Debug",
   "title-name": "Debug",
   "5title": "Debug",
}
//valid identifiers
console.log(myObject.title); //Debug
console.log(myObject.$title); //Debug
console.log(myObject._title); //Debug
console.log(myObject.title9); //Debug

//not valid identifiers
console.log(myObject.title.name); //undefined
console.log(myObject.title-name); //NaN
console.log(myObject.5title); // throws SyntaxError: Unexpected number

But in Javascript, this does not mean that you cannot use this type of identifier. It means you can’t use them with this assessor method.

To solve this type of problem, we have other ways to access properties in Javascript Objects.

Method 2: Using Square brackets

The syntax for this method is also quite simple:

expression[expression]

This syntax is well known when we talk about Arrays, but as we know (or at least should know), in Javascript, Arrays are a special kind of object.

The first expression must be associated with an object, and the second expression must return or express the name of a property. We’ll understand better:

We can access the property by placing the name of the property directly within the brackets:

const myProfile = {
        title: "@EverythingDebug",
        url: "https://twitter.com/EverythingDebug",
        tweets: 9,
        followers: 4,
        following: 6
      };
console.log(myProfile['title']); // "@EverythingDebug"

Or, we can create a variable and associate it with the name of the property, for example:

const myProfile = {
        title: "@EverythingDebug",
        url: "https://twitter.com/EverythingDebug",
        tweets: 9,
        followers: 4,
        following: 6
      };

const myTitle = 'title';
const myFollowers = 'followers';
console.log(myProfile[myTitle]); // "@EverythingDebug"
console.log(myProfile[myFollowers]); // 4

Using this method to access properties in javascript objects, you can use the identifiers that were not possible with the first method:

const myObject = {
   "title.name": "Debug",
   "title-name": "Debug",
   "5title": "Debug",
}
//Using brackets to access objects properties
//the identifiers are are now valid
console.log(myObject['title.name']); //Debug
console.log(myObject['title-name']); //Debug
console.log(myObject['5title']); //Debug

You can use this method when the property is dynamic, i.e. it can be changed during program execution.

This method allows us to work with the properties in very interesting ways. Look at the example below, where I can access the properties of an Object dynamically.

const myForm = {
   input_1: "Name",
   input_2: "Last Name",
   input_3: "Age",
}

let size = Object.keys(myForm).length;
for (let i = 1; i < size + 1; i++) {
   console.log(myForm["input_" + i]);
}

This is by far not the best solution for this situation, but it serves as an example of how you can use this method.

Method 3: Object Destructuring

The destructuring assignment allows you to assign the properties of an array or object to variables using a syntax that looks like a literal array or object.

{ identifier } = expression;

To access properties in javascript objects using destructuring, you will use the syntax above. Where expression should be associated with an object and identifier to the name of the property, you would like to access.

To access properties in objects or Arrays, as we’ve seen you can do like this:

const title = myObject.title;
const name = myObject.name;

const title = myObject['title'];
const name = myObject['name'];

Now using destructuring syntax to access properties on objects, the same code above would look like this:

const { title, name } = myObject;

The syntax is cleaner and much more direct than the previous methods.

And we can access the value of the property, just as we would do with the variables in the first example:

const myObject = {title: 'My Title', name: 'My Name'};
const {title, name} = myObject;

console.log(name); // "My Name"
console.log(title); // "My Title"

const {title, name} = myObject is a destructuring that defines two variables, title and name, as the values of the properties with the same name.

You can use this method to extract as many properties as you need.

const { identifier1, identifier2, ..., identifierN } = expression;

Considerations about the method

The destructuring method has other very useful approaches that we are going to discuss now, which adds even more value to this method.

Alias variable

Se você quiser de acessar propriedades em objetos, mas precisa criar um nome de variável diferente do nome da propriedade, você pode usar o aliasing.

If you want to access properties on objects, but need to create a variable name different from the property name, you can use aliasing.

const { identifier: aliasIdentifier } = expression;

identificador é o nome da propriedade a ser acessada, nomeDaVariável é o nome da variável que você quer criar, e expressão deve ser associada à um objeto. Após a desestruturação, a variável nomeDaVariável contém o valor da propriedade.

identifier is the name of the property to access, aliasIdentifier is the name of the variable you want to create, and expression must be associated with an object. After destructuring, the variable aliasIdentifier contains the property value.

Here’s an example:

const myObject = {title: 'My Title', name: 'My Name'};
const {title: myObjectTitle} = myObject;

console.log(myObjectTitle); // "My Title"

 Dynamic property name

What makes destructuring objects even more useful is that you can extract for the properties of variables with dynamic values:

const { [expression]: identifier } = expression;

The first expression must be associated with the name of the property you want to extract, the identifier must indicate the variable name after destructuring, and the last expression must be associated with the object.

Let’s give an example:

const myTitle= 'title';

const myObject = {title: 'My Title', name: 'My Name'};
const {[myTitle]: myObjectTitle} = myObject;

console.log(myObjectTitle); // "My Title"

const {[myTitle]: myObjectTitle} = myObject is a destructuring of objects that dynamically, at runtime, determine which property to extract.

Bottom Line

As you can see there’re a lot of good ways to access properties in Javascript objects.

The first method, using the dot ., object.property works well when you know the variable in advance, and all your properties are valid properties.

Quando o nome da propriedade é dinâmica ou não é um identificador válido, uma alternativa melhor é utilizar o segundo método, e colocar a propriedade entre colchetes: object[propertyName].

When the property name is dynamic or not a valid identifier, a better alternative is to use the second method, and put the property within brackets: object[propertyName].

The object destructuring extracts the property for a variable directly: { property } = object. In addition, you can extract the properties dynamically (determined at runtime): { [propertName]: variable }. = object.

There are no good or bad ways to access the properties. Choose according to your particular situation.

See you next time!

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Comments