3 Ways To Access Object Properties in JavaScript

栏目: IT技术 · 发布时间: 4年前

内容简介:You can access the properties of an object in JavaScript using 3 ways:Let’s check in detail how each way to access the properties work. And understand when it’s reasonable to use one way or another depending on the situation.A common way to access the prop

You can access the properties of an object in JavaScript using 3 ways:

object.property
object['property']
const { property } = object

Let’s check in detail how each way to access the properties work. And understand when it’s reasonable to use one way or another depending on the situation.

1. Dot property accessor

A common way to access the property of an object is the dot property accessor syntax:

expression.identifier

expression should evaluate to an object, and identifier is the name of the property you’d like to access.

For example, let’s access the property name of the object hero :

const hero = {
  name: 'Batman'
};

// Dot property accessor
hero.name; // => 'Batman'

hero.name is a dot property accessor that reads the property name of the object hero .

You can use the dot property accessor in a chain to access deeper properties: object.prop1.prop2 .

Choose the dot property accessor when the property name is known ahead of time .

1.1 Dot property accessor requires identifiers

The dot property accessor works correctly when the property name is a valid identifier . An identifier in JavaScript contains Unicode letters, $ , _ , and digits 0..9 , but cannot start with a digit.

This is not a problem, because usually, the property names are valid identifiers: e.g. name , address , street , createdBy .

But sometimes properties are not valid identifiers:

const weirdObject = {
  'prop-3': 'three',
  '3': 'three'
};

weirdObject.prop-3; // => NaNweirdObject.3;      // throws SyntaxError: Unexpected number

Because prop-3 and 3 are invalid identifiers, the dot property accessor doesn’t work:

  • weirdObject.prop-3 evaluates to NaN , instead of the expected 'tree'
  • weirdObject.3 throws a SyntaxError !

Why does the expression weirdObject.prop-3 evaluate to NaN ? Please write your answer in a comment below!

To access the properties with these special names, use the square brackets property accessor (which is described in the next section):

const weirdObject = {
  'prop-3': 'three',
  '3': 'three'
};

weirdObject['prop-3']; // => 'three'weirdObject[3];        // => 'three' 

The square brackets syntax accesses without problems the properties that have special names: weirdObject['prop-3'] and weirdObject[3] .

2. Square brackets property accessor

The square brackets property accessor has the following syntax:

expression[expression]

The first expression should evaluate to an object and the second expression should evaluate to a string denoting the property name.

Here’s an example:

const property = 'name';
const hero = {
  name: 'Batman'
};

// Square brackets property accessor:
hero['name'];   // => 'Batman'hero[property]; // => 'Batman'

hero['name'] and hero[property] both read the property name by using the square brackets syntax.

Choose the square brackets property accessor when the property name is dynamic , i.e. determined at runtime.

3. Object destructuring

The basic object destructuring syntax is pretty simple:

const { identifier } = expression;

identifier is the name of the property to access and expression should evaluate to an object. After the destructuring, the variable identifier contains the property value.

Here’s an example:

const hero = {
  name: 'Batman'
};

// Object destructuring:
const { name } = hero;name; // => 'Batman'

const { name } = hero is an object destructuring. The destructuring defines a variable name with the value of property name .

When you get used to object destructuring, you will find that its syntax is a great way to extract the properties into variables.

Choose the object destructuring when you’d like to create a variable having the property value.

Note that you can extract as many properties as you’d like:

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

3.1 Alias variable

If you’d like to access the property, but create a variable name different than the property name, you could use aliasing.

const { identifier: aliasIdentifier } = expression;

identifier is the name of the property to access, aliasIdentifier is the variable name, and expression should evaluate to an object. After the destructuring, the variable aliasIdentifier contains the property value.

Here’s an example:

const hero = {
  name: 'Batman'
};

// Object destructuring:
const { name: heroName } = hero;heroName; // => 'Batman'

const { name: heroName } = hero is an object destructuring. The destucturing defines a new variable heroName (instead of name as in previous example), and assigns to heroName the value hero.name .

3.2 Dynamic property name

What makes the object destructuring even more useful is that you could extract to variables properties with the dynamic value:

const { [expression]: identifier } = expression;

The first expression should evaluate to a property name, and the identifier should indicate the variable name created after the destructuring. The second expression should evaluate to the object you’d like to destructure.

Here’s an example:

const property = 'name';
const hero = {
  name: 'Batman'
};

// Object destructuring:
const { [property]: name } = hero;name; // => 'Batman'

const { [property]: name } = hero is an object destructuring that dynamically, at runtime, determines what property to extract.

4. When the property doesn’t exist

If the accessed property doesn’t exist, all 3 accessor syntaxes evalute to undefined :

const hero = {
  characterName: 'Batman'
};

hero.name;    // => undefined
hero['name']; // => undefined
const { name } = hero;
name;         // => undefined

The property name doesn’t exist in the object hero . Thus the dot property accessor hero.name , square brackets property accessor hero['name'] and the variable name after destructuring evaluate to undefined .

5. Conclusion

JavaScript provides a bunch of good ways to access object properties.

The dot property accessor syntax object.property works nicely when you know the variable ahead of time.

When the property name is dynamic or is not a valid identifier, a better alternative is square brackets property accessor: object[propertyName] .

The object destructuring extracts the property directly into a variable: { property } = object . Moreover, you can extract the dynamic property names (determined at runtime): { [propertName]: variable } = object .

There are no good or bad ways to access properties. Choose depending on your particular situation.


以上所述就是小编给大家介绍的《3 Ways To Access Object Properties in JavaScript》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Rationality for Mortals

Rationality for Mortals

Gerd Gigerenzer / Oxford University Press, USA / 2008-05-02 / USD 65.00

Gerd Gigerenzer's influential work examines the rationality of individuals not from the perspective of logic or probability, but from the point of view of adaptation to the real world of human behavio......一起来看看 《Rationality for Mortals》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具