Currently, I have an object with integer keys for certain values. I do not know that each key actually exists on the object yet, however.
Usually, I would be able to perform
JavaScript
x
2
1
Object?.parentKey?.childKey
2
to find the value of childKey
, if it exists. If childKey is an integer, however, then
JavaScript
1
2
1
Object?.parentKey?.0
2
does not work.
JavaScript
1
2
1
Object['parentKey.0']
2
doesn’t work either. Is there any way to do this?
Advertisement
Answer
Issue
Object?.parentKey?.0
doesn’t work since valid javascript identifiers can’t start with a number.
In JavaScript, identifiers are case-sensitive and can contain Unicode letters,
$
,_
, and digits (0-9), but may not start with a digit.
Object['parentKey.0']
doesn’t work unless there’s a key that is literally "parentKey.0"
, i.e. { "parentKey.0": "value" }
Solution
Access like a dynamic object key (Computed Property Names)
JavaScript
1
2
1
object?.parentKey?.[0]
2
or
JavaScript
1
2
1
object?.parentKey?.['0']
2
JavaScript
1
7
1
const object = {
2
parentKey: {
3
0: 'hello world!',
4
},
5
};
6
7
console.log(object?.parentKey?.[0]);