Skip to content

Creating a dictionary Object from an Array #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 23, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions authors.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ The following people are totally rad and awesome because they have contributed r
* Jeff Pickhardt *pickhardt (at) gmail (dot) com*
* Frederic Hemberger
* Mike Hatfield *oakraven13@gmail.com*
* [Anton Rissanen](http://github.com/antris) *hello@anton.fi*
* ...You! What are you waiting for? Check out the [contributing](/contributing) section and get cracking!

# Developers
Expand Down
63 changes: 63 additions & 0 deletions chapters/arrays/creating-a-dictionary-object-from-an-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
layout: recipe
title: Creating a dictionary Object from an Array
chapter: Arrays
---
## Problem

You have an Array of Objects, such as:

{% highlight coffeescript %}
cats = [
{
name: "Bubbles"
age: 1
},
{
name: "Sparkle"
favoriteFood: "tuna"
}
]
{% endhighlight %}

But you want to access it as a dictionary by key, like `cats["Bubbles"]`.

## Solution

You need to convert your array into an Object. Use reduce for this.

{% highlight coffeescript %}
# key = The key by which to index the dictionary
Array::toDict = (key) ->
@reduce ((dict, obj) -> dict[ obj[key] ] = obj if obj[key]?; return dict), {}
{% endhighlight %}

To use this:

{% highlight coffeescript %}
catsDict = cats.toDict('name')
catsDict["Bubbles"]
# => { age: 1, name: "Bubbles" }
{% endhighlight %}

## Discussion

Alternatively, you can use an Array comprehension:

{% highlight coffeescript %}
Array::toDict = (key) ->
dict = {}
dict[obj[key]] = obj for obj in this when obj[key]?
dict
{% endhighlight %}

If you use Underscore.js, you can create a mixin:

{% highlight coffeescript %}
_.mixin toDict: (arr, key) ->
throw new Error('_.toDict takes an Array') unless _.isArray arr
_.reduce arr, ((dict, obj) -> dict[ obj[key] ] = obj if obj[key]?; return dict), {}
catsDict = _.toDict(cats, 'name')
catsDict["Sparkle"]
# => { favoriteFood: "tuna", name: "Sparkle" }
{% endhighlight %}