根据另一个数组中对象的属性创建一个数组 [英] Creating an array from properties of objects in another array
问题描述
是否有任何方便的方法来获取对象的数组/集合并创建一个包含第一个数组中每个项目的某些属性的新数组/集合?
Is there any convenient way to take an array/set of objects and create a new array/set containing some property of each item in the first array?
例如,一个数组包含Car对象.我需要一个licensePlates数组,其中每辆车都有一个NSObject car.licensePlate.
For example, an array contains Car objects. I need an array of licensePlates, where each car has an NSObject car.licensePlate.
目前,我只是遍历第一个将对象添加到可变结果数组中的数组,但是想知道是否存在一种实例化方法(请检查NSArray文档).
Currently I just iterate through the first array adding objects to my mutable results array, but was wondering if there is an instantiation method that exists for this (checked the docs for NSArray).
推荐答案
这将返回一个数组,其中包含myCars
数组中每个项目的licensePlate
值:
This will return an array containing the value of licensePlate
from each item in the myCars
array:
NSArray *licensePlates = [myCars valueForKeyPath:@"licensePlate"]
例如,如果只需要唯一项,则可以执行以下操作:
If you want only unique items (for example), you can do something like this:
NSArray *licensePlates = [myCars valueForKeyPath:@"@distinctUnionOfObjects.licensePlate"];
有关更多可能性,请参见键值编码编程指南.
For more possibilities, see the Collection Operators documentation in the Key-Value Coding Programming Guide.
这篇关于根据另一个数组中对象的属性创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!