CoffeeScript 对象数组

对象数组

问题

你想要得到一个与你的某些属性匹配的数组对象。

你有一系列的对象,如:

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

你想用某些特征来滤出想要的对象。例如:猫的位置({ 年龄: 1 }) 或者猫的位置({ 年龄: 1 , 最爱的食物: “老鼠” })

解决方案

你可以像这样来扩展数组:

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"
# => []

讨论

这是一个确定的匹配。我们能够让匹配函数更加灵活:

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"
# => []
# its case sensitive

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

处理收集的一种方式可以被叫做“find” ,但是像underscore或者lodash这些库把它叫做“where” 。

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/coffeescript/10663.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年2月26日
下一篇 2023年2月26日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注