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

Object?.parentKey?.childKey

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

Object?.parentKey?.0

does not work.

Object['parentKey.0']

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)

object?.parentKey?.[0]

or

object?.parentKey?.['0']

const object = {
  parentKey: {
    0: 'hello world!',
  },
};

console.log(object?.parentKey?.[0]);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement