how to get a model by array params from a collection

天大地大妈咪最大 提交于 2019-12-11 11:44:34

问题


I have a model like this:

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

and I have a collection containing these kind of models. The collection needs to filter by from. I know _.where an underscore.js function. I am using it like this:

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

and need to filter by 'to' as well:

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

it does not work, because to is an array. How can I filter by to ? I would be grateful if someone helped me out !


回答1:


At that point you need to use _.filter. If you look at the source code you can see that _.where is just a helpful wrapper around _.filter. _.where is good for simple filtering based on primitive comparison, but anything more complex you will have to write yourself.

# Filter for messages that contain the target address.
matchedTo = _.filter msgs, (msg) -> _.contains msg.to, login

# Pluck as usual
toIds = _.pluck matchedTo, 'msgId'


来源:https://stackoverflow.com/questions/16008356/how-to-get-a-model-by-array-params-from-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!