1

嗨,我的控制器中有收藏品,例如

def devices=[ [id:PPL000000011906, firstName:Adam, lastName:Baines], [id:PPL000000010836, firstName:Adam, lastName:Baines], [id:PPL000000015137, firstName:Adan, lastName:Saenz], [id:PPL000000015136, firstName:Adan, lastName:Saenz]]

我将从我的视图中获取 id。如何根据 ID 从我的地图中获取名字和姓氏值。

谢谢,湿婆

4

2 回答 2

3

基本上,您可以使用find给定的id. 这是一个例子

def devices = [ [id:'PPL000000011906', firstName:'Adam', lastName:'Baines'],
                [id:'PPL000000010836', firstName:'Adam', lastName:'Baines'],
                [id:'PPL000000015137', firstName:'Adan', lastName:'Saenz'],
                [id:'PPL000000015136', firstName:'Adan', lastName:'Saenz'] ]

Closure<String> nameForId = { String id ->
  devices.find { it.id == id }?.with { map ->
    "$map.firstName $map.lastName"
  }
}

assert nameForId( 'PPL000000015136' ) == 'Adan Saenz'
于 2012-10-31T10:04:08.223 回答
0

我会这样做以获得一个字段:

devices.find { it.id == 'PPL000000011906' }?.firstName

如果你想要闭包和参数,我会这样做:

def findPerson = { person -> devices.find { it.id == person }  }
def myPerson = findPerson('PPL000000011906')
println "FirstName: ${myPerson?.firstName} LastName: ${myPerson?.lastName}"

如果你想发疯,你可以这样做:

ArrayList.metaClass.findThingInMap = { field, value -> delegate.find { it[field] == value } }

这样做是允许您在任何包含哈希映射的数组列表中找到字段的值,这就是您所拥有的。

def myPerson = devices.findThingInMap('id', 'PPL000000011906')
println "FirstName: ${myPerson?.firstName} LastName: ${myPerson?.lastName}"

除非您需要灵活性,否则我不会真正这样做,但这显示了 groovy 的真正力量和令人敬畏。

于 2016-04-09T20:35:52.490 回答