Skip to content

Commit c694b05

Browse files
committed
Merge pull request #52 from antris/arr2dict
Creating a dictionary Object from an Array
2 parents 623d696 + 17d6e49 commit c694b05

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

authors.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ The following people are totally rad and awesome because they have contributed r
2020
* Jeff Pickhardt *pickhardt (at) gmail (dot) com*
2121
* Frederic Hemberger
2222
* Mike Hatfield *oakraven13@gmail.com*
23+
* [Anton Rissanen](http://github.com/antris) *hello@anton.fi*
2324
* ...You! What are you waiting for? Check out the [contributing](/contributing) section and get cracking!
2425

2526
# Developers
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
---
2+
layout: recipe
3+
title: Creating a dictionary Object from an Array
4+
chapter: Arrays
5+
---
6+
## Problem
7+
8+
You have an Array of Objects, such as:
9+
10+
{% highlight coffeescript %}
11+
cats = [
12+
{
13+
name: "Bubbles"
14+
age: 1
15+
},
16+
{
17+
name: "Sparkle"
18+
favoriteFood: "tuna"
19+
}
20+
]
21+
{% endhighlight %}
22+
23+
But you want to access it as a dictionary by key, like `cats["Bubbles"]`.
24+
25+
## Solution
26+
27+
You need to convert your array into an Object. Use reduce for this.
28+
29+
{% highlight coffeescript %}
30+
# key = The key by which to index the dictionary
31+
Array::toDict = (key) ->
32+
@reduce ((dict, obj) -> dict[ obj[key] ] = obj if obj[key]?; return dict), {}
33+
{% endhighlight %}
34+
35+
To use this:
36+
37+
{% highlight coffeescript %}
38+
catsDict = cats.toDict('name')
39+
catsDict["Bubbles"]
40+
# => { age: 1, name: "Bubbles" }
41+
{% endhighlight %}
42+
43+
## Discussion
44+
45+
Alternatively, you can use an Array comprehension:
46+
47+
{% highlight coffeescript %}
48+
Array::toDict = (key) ->
49+
dict = {}
50+
dict[obj[key]] = obj for obj in this when obj[key]?
51+
dict
52+
{% endhighlight %}
53+
54+
If you use Underscore.js, you can create a mixin:
55+
56+
{% highlight coffeescript %}
57+
_.mixin toDict: (arr, key) ->
58+
throw new Error('_.toDict takes an Array') unless _.isArray arr
59+
_.reduce arr, ((dict, obj) -> dict[ obj[key] ] = obj if obj[key]?; return dict), {}
60+
catsDict = _.toDict(cats, 'name')
61+
catsDict["Sparkle"]
62+
# => { favoriteFood: "tuna", name: "Sparkle" }
63+
{% endhighlight %}

0 commit comments

Comments
 (0)