1

我有一个已解析的查询字符串对象 ,req.query并且我想查看该对象是否具有三个键中的任何foo一个: 、barbaz

有没有一种使用 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
  ...

还有比这些更好的方法吗?不管怎样,你会写什么?

4

3 回答 3

4

怎么用pick

if !_.isEmpty(_(req.query).pick("foo", "bar", "baz"))
  ...
于 2012-12-02T08:33:37.837 回答
2

怎么样:

queryKeys = _.keys(req.query)
if _(queryKeys).intersection(['foo', 'bar', 'baz']).length
  ...
于 2012-12-02T18:48:41.723 回答
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赢得清晰和效率。

于 2012-12-04T05:09:59.067 回答