Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

For example, an array contains Car objects. I need an array of licensePlates, where each car has an NSObject car.licensePlate.

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).

like image 552
Ben Packard Avatar asked Mar 27 '12 13:03

Ben Packard


People also ask

Can object properties be arrays?

Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() .


1 Answers

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.

like image 102
Mike Weller Avatar answered Oct 30 '22 21:10

Mike Weller