【问题标题】:how to get a model by array params from a collection如何通过集合中的数组参数获取模型
【发布时间】:2013-04-15 13:50:12
【问题描述】:

我有一个这样的模型:

model = 
    from: "a@b.com"
    id: 1
    to: [c@d.com]

我有一个包含这些模型的集合。该集合需要通过from 过滤。我知道_.where 一个underscore.js 函数。我是这样使用它的:

fromIds = _.pluck _.where(msgs, from : login), 'msgId' 

还需要按“to”过滤:

toIds = _.pluck _.where(msgs, to : login), 'msgId' 

它不起作用,因为to 是一个数组。如何按to 过滤?如果有人帮助我,我将不胜感激!

【问题讨论】:

    标签: javascript backbone.js coffeescript underscore.js


    【解决方案1】:

    此时您需要使用_.filter。如果您查看source code,您会发现_.where 只是_.filter 的有用包装。 _.where 适用于基于原始比较的简单过滤,但更复杂的内容您必须自己编写。

    # Filter for messages that contain the target address.
    matchedTo = _.filter msgs, (msg) -> _.contains msg.to, login
    
    # Pluck as usual
    toIds = _.pluck matchedTo, 'msgId'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 2011-09-20
      • 2019-01-12
      • 2016-03-18
      • 1970-01-01
      • 2018-09-11
      • 2019-01-28
      • 1970-01-01
      相关资源
      最近更新 更多