99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

CoffeeScript 由數(shù)組創(chuàng)建一個對象詞典

2022-06-29 16:53 更新

由數(shù)組創(chuàng)建一個對象詞典

問題

你有一組對象,例如:

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

但是你想讓它像詞典一樣,可以通過關鍵字訪問它,就像使用cats["Bubbles"]。

解決方案

你需要將你的數(shù)組轉換為一個對象。通過這樣使用reduce:

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

使用它時像下面這樣:

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

討論

另一種方法是使用數(shù)組推導:

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

如果你使用Underscore.js,你可以創(chuàng)建一個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" }
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號