用于查询多个对象键的Underscore.js或CoffeeScript习惯用法?

时间:2012-12-02 08:03:36

标签: javascript coffeescript underscore.js

我有一个已解析的查询字符串对象req.query,我想看看该对象是否有任意三个键:foobarbaz

是否有使用Underscore和/或CoffeeScript查询的惯用方式?

# simple and direct but not very DRY:
if req.query.foo or req.query.bar or req.query.baz
  ..

# using the any filter combined w/ CS's in sugar:
if _(req.query).any (val, key) -> key in ['foo', 'bar', 'baz']
  ..

# plucking just the desired keys:
if _(req.query).pick('foo', 'bar', 'baz').keys().length
  ...

还有比其中任何一种更好的方法吗?无论哪种方式,你会写什么?

3 个答案:

答案 0 :(得分:4)

如何使用pick

if !_.isEmpty(_(req.query).pick("foo", "bar", "baz"))
  ...

答案 1 :(得分:2)

怎么样:

queryKeys = _.keys(req.query)
if _(queryKeys).intersection(['foo', 'bar', 'baz']).length
  ...

答案 2 :(得分:1)

一些替代方案:

# Helper function:
# ----------------
_has = (obj, arr) -> (1 for key in arr when obj.hasOwnProperty(key)).length > 0

if _has req.query, ['foo', 'bar', 'baz']
    ...

# Extending `Object`:
# -------------------
Object::has = (arr) ->
    while arr.length && not result = @hasOwnProperty arr.shift() then
    result

if req.query.has ['foo', 'bar', 'baz']
    ...

# Using native `Array::some`:
# ---------------------------
if ['baz', 'bar', 'foo'].some {}.hasOwnProperty.bind req.query
    # ...

其实我会写这个:

if (true for key in ['foo', 'bar', 'baz'] when req.query[k]).length

但仅当列表长于此列表时,否则简单if query.foo or query.bar or query.baz会因清晰度和效率而获胜。