CoffeeScript 對(duì)象數(shù)組

2022-06-29 16:56 更新

對(duì)象數(shù)組

問(wèn)題

你想要得到一個(gè)與你的某些屬性匹配的數(shù)組對(duì)象。

你有一系列的對(duì)象,如:

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

你想用某些特征來(lái)濾出想要的對(duì)象。例如:貓的位置({ 年齡: 1 }) 或者貓的位置({ 年齡: 1 , 最?lèi)?ài)的食物: "老鼠" })

解決方案

你可以像這樣來(lái)擴(kuò)展數(shù)組:

Array::where = (query) ->
    return [] if typeof query isnt "object"
    hit = Object.keys(query).length
    @filter (item) ->
        match = 0
        for key, val of query
            match += 1 if item[key] is val
        if match is hit then true else false

cats.where age:1
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 },{ name: 'flyingCat', favoriteFood: 'mice', age: 1 } ]

cats.where age:1, name: "Bubbles"
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]

cats.where age:1, favoriteFood:"tuna"
# => []

討論

這是一個(gè)確定的匹配。我們能夠讓匹配函數(shù)更加靈活:

Array::where = (query, matcher = (a,b) -> a is b) ->
    return [] if typeof query isnt "object"
    hit = Object.keys(query).length
    @filter (item) ->
        match = 0
        for key, val of query
            match += 1 if matcher(item[key], val)
        if match is hit then true else false

cats.where name:"bubbles"
# => []
# it's case sensitive

cats.where name:"bubbles", (a, b) -> "#{ a }".toLowerCase() is "#{ b }".toLowerCase()
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]
# now it's case insensitive

處理收集的一種方式可以被叫做“find” ,但是像underscore或者lodash這些庫(kù)把它叫做“where” 。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)