groovy和grails-如何遍历对象数组?

groovy和grails-如何遍历对象数组?,grails,groovy,each,Grails,Groovy,Each,我有一个Person-object-Person.first-Person.last数组 要确定此人是否有名字,我必须在阵列上运行 我尝试了以下操作,但出现错误: person.eachWithIndex { String persons, i -> if(persons.first=='') println(''error) } 我应该如何操作对象数组?您是否在寻找类似于: class Person { def first def last } def persons =

我有一个Person-object-Person.first-Person.last数组

要确定此人是否有名字,我必须在阵列上运行

我尝试了以下操作,但出现错误:

person.eachWithIndex { String persons, i ->
if(persons.first=='')
println(''error)
}

我应该如何操作对象数组?

您是否在寻找类似于:

class Person {
   def first
   def last
}

def persons = [ new Person(first:'',last:'last'), new Person(first:'john',last:'anon')]

persons.eachWithIndex { person, i ->
    if(person.first==''){
      println("error at person in position $i")
    }
}
由于您没有添加更多详细信息,所以当您说操纵对象数组时,我不知道您在寻找什么,因此有一些示例:

要操作数组对象,您可以在each本身中添加语句,例如添加一个notDefined作为first for person,其中first==您可以使用:

persons.eachWithIndex { person, i ->
    if(person.first==''){
      person.first = 'notDefined'
      println("first as notDefined for person in position $i")
    }
}
要删除first==中的元素,可以使用removeAll方法从数组中删除不需要的元素:

persons.removeAll { person -> 
    !person.first
}
根据评论进行编辑:

如果要从列表中删除空元素,可以使用注释中使用的表达式:

def persons = [ new Person(first:'pepe',last:'last'), null]
persons.removeAll([null])
println persons.size() // prints 1 since null element is removed
但是,似乎您并没有尝试删除null元素,而是尝试删除所有属性都为null的元素,在您的示例中,您希望删除:new Personfirst:null,last:null。为此,您可以尝试使用以下代码:

def persons = [ new Person(first:'pepe',last:'last'), new Person(first:null,last:null)]

persons.removeAll{ person ->
    // get all Person properties wich value is not null
    // without considering class propertie wich is implicit in all classes
    def propsNotNull = person.properties.findAll { k,v -> v != null && k != 'class' }
    // if list is empty... means that all properties are null
    return propsNotNull.isEmpty()
}

println persons.size() // prints 1

希望这能有所帮助,

@albciff-以防我的对象的所有属性都为空。如何删除它们?我尝试了邀请。removeAll[null],但无效