以下是一个示例代码,展示如何根据另一个标记为true的子键对象来过滤数组对象:
def filter_array_objects(array, key):
filtered_array = []
for obj in array:
if obj.get(key, False):
filtered_array.append(obj)
return filtered_array
# 示例数据
array = [
{'name': 'John', 'active': True},
{'name': 'Jane', 'active': False},
{'name': 'Michael', 'active': True},
{'name': 'Emma', 'active': True}
]
# 按照'active'子键为True过滤数组对象
filtered_array = filter_array_objects(array, 'active')
# 打印过滤后的数组对象
for obj in filtered_array:
print(obj)
输出结果:
{'name': 'John', 'active': True}
{'name': 'Michael', 'active': True}
{'name': 'Emma', 'active': True}
在示例中,filter_array_objects
函数接受一个数组对象和一个键名作为参数。它遍历数组中的每个对象,使用get
方法获取指定键的值,默认为False
。如果该值为True
,则将该对象添加到filtered_array
中。最后,返回过滤后的数组对象。
在示例数据中,我们有一个包含不同人员信息的数组对象。我们使用'active'
作为键名,过滤出具有True
值的对象。最后,我们打印出过滤后的数组对象。