Consider the following array:
snacksArray = [{'cookies':'delicious'},{'brownies':'scrumptious'}]
If I were to retrieve snacksArray[0]
, I would get {'cookies':'delicious'}
. Now, let's say I added an object to this array like this:
snacksArray.push({[treat]:yumminess})
However, when attempting to access the keys cookies
or brownies
in each object within this array, I encounter issues. Trying snacksArray[0].treat
results in undefined.
Typically, when assigning a value/variable to a key of an object, they should be encased in square brackets. So how do we go about extracting values from them later on when these objects are part of an array, as illustrated in the example above? I attempted using Object.keys(snacksArray[index])
, but this only provides me with the keys themselves rather than allowing me to extract the specific value associated with that particular key.
In summary: How can we extract the value paired with a key within an object that is contained in an array, particularly when the keys are strings akin to the instance below?
snacksArray = [{'cookies':'delicious'},{'brownies':'scrumptious'}]