简体   繁体   English

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

[英]Underscore.js or CoffeeScript idiom for querying multiple object keys?

I have a parsed query string object, req.query , and I want to see if that object has any of three keys: foo , bar , baz . 我有一个解析的查询字符串对象req.query ,我想看看该对象是否具有三个键中的任何一个: foobarbaz

Is there an idiomatic way of querying that with Underscore and/or CoffeeScript? 是否有一种惯用的方式使用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
  ...

Is there another way better than any of these? 有没有比这些方法更好的方法了? Either way, what would you write? 不管怎样,你会写什么?

How about using pick ? 使用pick怎么样?

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

How about: 怎么样:

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

Some alternatives: 一些替代方案:

# 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
    # ...

Actually I would write this: 实际上,我会这样写:

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

but only if the list is longer than that, otherwise the simple if query.foo or query.bar or query.baz wins for clarity and efficiency. 但仅当列表长if query.foo or query.bar or query.baz列表时,否则, if query.foo or query.bar or query.baz可以提高清晰度和效率, if query.foo or query.bar or query.baz胜出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM