将 coffeescript 中的记录数组过滤为 return 所有年龄 > 50 的记录

Filtering an array of records in coffeescript to return all records with age > 50

鉴于这种数据集

records = [
  {id: 1, name: "John Smith", age: 49},
  {id: 2, name: "Jane Brown", age: 45},
  {id: 3, name: "Tim Jones",  age: 60},
  {id: 4, name: "Blake Owen", age: 78}    
]

如何将记录筛选为 return 刚好超过 50 岁的缩减数组。

假设 return 数组是

over50s = // something

我看过很多类似的代码,但它们对我来说非常适合。

感谢您的帮助!

这个示例脚本怎么样?使用 filter().

检索结果 over50s

示例脚本:

records = [
  {id: 1, name: "John Smith", age: 49},
  {id: 2, name: "Jane Brown", age: 45},
  {id: 3, name: "Tim Jones",  age: 60},
  {id: 4, name: "Blake Owen", age: 78}
]
over50s = records.filter (e) -> e.age >= 50

结果:

[
    { id: 3, name: 'Tim Jones',  age: 60 },
    { id: 4, name: 'Blake Owen', age: 78 }
]

如果我误解了你的问题,请告诉我。我要修改。

答案很完美,但我想使用 comprehensions:

添加“Coffeescript 方式”
 over50s = (record for record in records when record.age > 50)

解释:

for record in records
  console.log(record)
# This would loop over the records array, 
#   and each item in the array will be accessible 
#   inside the loop as `record`

console.log(record) for record in records
# This is the single line version of the above

console.log(record) for record in records when record.age > 50
# now we would only log those records which are over 50

over50s = (record for record in records when record.age > 50)
# Instead of logging the item, we can return it, and as coffeescript
#   implicitly returns from all blocks, including comprehensions, the 
#   output would be the filtered array
# It's shorthand for:
    
over50s = for record in records
  continue unless record.age > 50
  record

# This long hand is better for complex filtering conditions. You can
#   just keep on adding `continue if ...` lines for every condition
# Impressively, instead of ending up with `null` or `undefined` values
#   in the filtered array, those values which are skipped by `continue`
#   are completely removed from the filtered array, so it will be shorter.