Skip to content
Advertisement

Getting the value associated with an integer key from an object, if the key exists (JavaScript)

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

to find the value of childKey, if it exists. If childKey is an integer, however, then

JavaScript

does not work.

JavaScript

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

or

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement