|
| 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