你有一組對象,例如:
cats = [
{
name: "Bubbles"
age: 1
},
{
name: "Sparkle"
favoriteFood: "tuna"
}
]
但是你想讓它像詞典一樣,可以通過關(guān)鍵字訪問它,就像使用 cats["Bubbles"]。
你需要將你的數(shù)組轉(zhuǎn)換為一個對象。通過這樣使用 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ù)組推導(dǎo):
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" }