JavaScript – Object or Array or Facade?

GitHub Code

I discovered something interesting today.  Apparently, you can treat an object like an array…or so I thought.  Reviewing a colleague’s code showed that you can add key/value entries to an existing object in a manner I would have associated with an array.  But, wait…its not an array 🙂

  • While simple in concept once you get it, it is a bit confusing when you first review it.  Running the sample doesn’t show anything terribly unusual as we see an object with properties.  Also not surprising is that we can print the properties out like an array using Object.keys.

screen-shot-2017-02-27-at-9-13-12-pm

  • Now, looking at the code, you can see we create an object.  It gets weird when you see how the other properties are added (i.e. very array like).  Kinda cool!

screen-shot-2017-02-27-at-9-03-57-pm

Stay tuned!

References

  1. http://stackoverflow.com/questions/33381583/how-to-add-many-values-to-one-key-in-javascript-object
  2. Chris Fahnert (credit for this method)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s