2014-10-01 7 views
6

Ho bisogno di dove ma con non caso. Per esempio, mi piacerebbe trovare giochi, che non hanno nome "Shakespeare":Come creare il caso `where not`?

_.where(listOfPlays, {author: !"Shakespeare", year: 1611}); 
           ^^^^^^^^^^^^^ 
          NOT Shakespeare 

Come posso farlo con underscore?

risposta

8
_.filter(listOfPlays, function(play) { 
    return play.author !== 'Shakespeare' && play.year === 1611; 
}); 

http://underscorejs.org/#filter

where non è altro che un wrapper conveniente intorno filter:

// Convenience version of a common use case of `filter`: selecting only objects 
// containing specific `key:value` pairs. 
_.where = function(obj, attrs) { 
    return _.filter(obj, _.matches(attrs)); 
}; 

https://github.com/jashkenas/underscore/blob/a6c404170d37aae4f499efb185d610e098d92e47/underscore.js#L249

+1

credo, sarebbe utile avere _.not() '' involucro pure. Ad esempio, '_.not (listOfPlays, {author:" Shakespeare "})'. – Warlock

0

Prova questo:

_.filter(listOfPlays,function(i){ 
    return i['author']!='Shakespeare' && i['year']==1611; 
}); 
7

si può cucinare il proprio "non dove" versione di _.where come questo

_.mixin({ 
    "notWhere": function(obj, attrs) { 
     return _.filter(obj, _.negate(_.matches(attrs))); 
    } 
}); 

E poi si può scrivere il codice come questo

_.chain(listOfPlays) 
    .where({ 
     year: 1611 
    }) 
    .notWhere({ 
     author: 'Shakespeare' 
    }) 
    .value(); 

Nota:_.negate è disponibile solo da v1. 7.0. Quindi, se si utilizza la versione precedente di _, si potrebbe desiderare di fare qualcosa di simile

_.mixin({ 
    "notWhere": function(obj, attrs) { 
     var matcherFunction = _.matches(attrs); 
     return _.filter(obj, function(currentObject) { 
      return !matcherFunction(currentObject); 
     }); 
    } 
}); 
+0

sì, sarebbe bello! Grazie! Un'osservazione, sarebbe meglio nominare la funzione come 'not()'. – Warlock

+0

@Warlock abbiamo già una funzione chiamata ['_.negate'] (http://underscorejs.org/#negate), quindi' not' e 'negate' potrebbero confondere ... – thefourtheye

+0

Ok, capisco. Grazie! – Warlock

0

Un sacco di risposte giuste, ma tecnicamente il PO appena chiesto di negare. Puoi anche usare rifiutare, è essenzialmente l'opposto del filtro. Per ottenere la condizione composta del 1611 e non Shakespeare:

_.reject(_.filter(listOfPlays, function(play){ 
    return play.year === 1611 
}), function(play) { 
    return play.author === 'Shakespeare'; 
}); 
Problemi correlati