首页 > 解决方案 > 如何根据使用 groovy 的条件从列表数组中删除列表?

问题描述

我是 groovy 的新手,如果整个列表不符合条件,我需要帮助删除它这是 JSON -

{
  "School" : New Elementary School,
  "District" : "District1",
  "City" : "NewTown",
     "Students" : [ {
     "Name": "Student1",
     "Grade": "1"    
    }, {
     "Name": "Student2",
     "Grade": "2"
    }, {
     "Name": "Student3",
     "Grade": "1"  
    }, {
     "Name": "Student4",
     "Grade": "1"  
    }, {
     "Name": "Student5",
     "Grade": "1"   
    } ],
}

我想要一个仅包含 1 年级学生的 JSON,即删除 Student2。输出应该是——

{
  "School" : New Elementary School,
  "District" : "District1",
  "City" : "NewTown",
     "Students" : [ {
     "Name": "Student1",
     "Grade": "1"    
    },  {
     "Name": "Student3",
     "Grade": "1"  
    }, {
     "Name": "Student4",
     "Grade": "1"  
    }, {
     "Name": "Student5",
     "Grade": "1"   
    } ],
}

我有适当的循环和条件。我在网上查找要删除整个列表,但似乎找不到任何东西。

标签: groovy

解决方案


您可以使用removeAll函数来执行此操作。例子

List a = [[a:1],[a:2],[a:1]]
a.removeAll{ it.a==2 }
print(a)
[[a:1], [a:1]]

在你的情况下

students = students.removeAll{ it.Grade == "2" }

推荐阅读