3 Ways To Access Object Properties in JavaScript

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

内容简介: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

第三次浪潮

第三次浪潮

托夫勒 / 黄明坚 / 中信出版社 / 2006-6 / 38.00元

《第三次浪潮》作者托夫勒在20多年前预见的未来是:跨国企业将盛行;电脑发明使SOHO(在家工作)成为可能;人们将摆脱朝九晚五工作的桎梏;核心家庭的瓦解;DIY(自己动手做)运动的兴起……时过境迁,如今我们才发现托夫勒的预言竟大多已成为了现实。   20年前的《第三次浪潮》在打开国门之初给人们心灵造成的冲击,其影响至今仍然连绵不绝。托夫勒在这本书中将人类社会划分为三个阶段:第一次浪潮为农业阶段......一起来看看 《第三次浪潮》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具