There are two main (others as well, which do not fall within the scope of this answer) ways to access properties in an object. See more in "property accessors" in the documentation.
The first of these is the dot notation - for example object.property
. In this case, how the access is "hard-coded" in the code, you cannot use when you need a dynamic access.
The benefit of this mode is greater readability. You can use point notation to access any property that is a identifier valid in Javascript. This way, you can access a property using dot notation as long as it is composed of Unicode letters, $
, _
and do not start with numbers.
So:
const myObj = {
1: 'One',
2: 'Two',
π: Math.PI, // "PI" é uma letra válida no Unicode
name: 'Bob',
$: 'jQuery?'
};
// myObj.1; --> Inválido porque 1 não é identificador válido
// myObj.2; --> Inválido porque 2 não é identificador válido
console.log(myObj.π); // 3.141592653589793
console.log(myObj.name); // Bob
console.log(myObj.$); // jQuery?
The other main access method uses square bracket notation [
and ]
, whose syntax is object[property]
. This notation is commonly used when you need to access the property dynamically or when the property name is not a valid identifier.
As seen above, this property should also be used to access properties other than valid Javascript identifiers.
They are also used to access properties whose key is a number (number
) or symbol (symbol
).
So:
const SYMBOL_KEY = Symbol('name');
const obj = {
1: 'One',
[SYMBOL_KEY]: 'Bob',
age: 10,
'not-a-valid-identifier': 'Value'
};
console.log(obj[1]); // One
console.log(obj[SYMBOL_KEY]); // Bob
console.log(obj['age']); // 10
console.log(obj['not-a-valid-identifier']); // Value
In the Ecmascript 2020 edition, Javascript allows you to use the optional access properties of objects. It works with both square bracket notation and point notation. It is useful for nested accesses.
Access would be Access?
– novic
@Virgilionovic in Portuguese (Portugal), Access = Access
– Tiago Martins Peres 李大仁
Here is Portuguese of Brazil so of the question. And on the question I believe that when you need to access by square bracket with those problems (spaces and hyphens) the problem is in the object that should follow another convention.
– novic
access - 1 - transitive and intransitive verb . Say yes; agree. = ANUIR, CONFORMAR-SE 2 - transitive verb - Having or obtaining access to (e.g., accessing a space, accessing a computer).(Latin Accedo, -ere, go to, approach) ---- "access", in Dicionário Priberam da Língua Portuguesa https://dicionario.priberam.org/aceder [retrieved 22-07-2020].
– user60252
@novic is not "Brazilian Portuguese". As already discussed in Meta, being Portuguese is what matters. No specific country is defined, and edits to change "region" are usually reversed.
– Bacco