Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript creates an object dictionary from an array


May 09, 2021 CoffeeScript


Table of contents


An object dictionary is created by an array

Problem

You have a set of objects, such as:

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

But you want it to be like a dictionary, accessing it through keywords, just like using cats.

Solution

You need to convert your array to an object. By using reduce in this way:

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

Use it like this:

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

Discuss

Another approach is to use arrays to infer:

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

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

_.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" }