如何将 NSDictionarys 的 NSArray 转换为 NSDictionarys 的嵌套 NSArray
如果我有一个带有多个字典对象(每个字典都是一个人)的 NSArray (或可变数组),如下所示:
[
{ forename: chris, surname: smith, age: 22 }
{ forename: paul, surname: smith, age: 24 }
{ forename: dave, surname: jones, age: 21 }
{ forename: alan, surname: jones, age: 26 }
{ forename: cecil, surname: reeves, age: 32 }
{ forename: pablo, surname: sanchez, age: 42 }
]
我如何将其分成四个数组的数组,按姓氏(并在该名字内)排序,如下所示:
[
[
{ forename: alan, surname: jones, age: 26 }
{ forename: dave, surname: jones, age: 21 }
]
[
{ forename: cecil, surname: reeves, age: 32 }
]
[
{ forename: pablo, surname: sanchez, age: 42 }
]
[
{ forename: chris, surname: smith, age: 22 }
{ forename: paul, surname: smith, age: 24 }
]
]
If I have an NSArray (or mutable array) with several dictionary objects (each dictionary is a Person) like this:
[
{ forename: chris, surname: smith, age: 22 }
{ forename: paul, surname: smith, age: 24 }
{ forename: dave, surname: jones, age: 21 }
{ forename: alan, surname: jones, age: 26 }
{ forename: cecil, surname: reeves, age: 32 }
{ forename: pablo, surname: sanchez, age: 42 }
]
How would I separate it into an array of four arrays, sorted by surname (and within that forename), like so:
[
[
{ forename: alan, surname: jones, age: 26 }
{ forename: dave, surname: jones, age: 21 }
]
[
{ forename: cecil, surname: reeves, age: 32 }
]
[
{ forename: pablo, surname: sanchez, age: 42 }
]
[
{ forename: chris, surname: smith, age: 22 }
{ forename: paul, surname: smith, age: 24 }
]
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用键值编码和谓词做一些非常简洁的事情...
这适用于
Person
对象(这会更好)或字典,只要字典有>@"surname"
键或Person
对象有一个-(NSString *)surname
方法。You can do some pretty neat stuff using key-value coding and predicates...
This will work for either a
Person
object (which would be better) or dictionaries, as long as the dictionaries have a@"surname"
key or thePerson
object has a-(NSString *)surname
method.您应该使用专门的 Person 类,而不是 NSDictionary。
您可以首先将其分组为字典数组的字典,例如,
如果您确实需要一个数组,则可以使用
[result allValues]
。如果需要排序数组,则需要手动排序:
You should use a specialized Person class, instead of an NSDictionary.
You could first group it into Dictionary of Arrays of Dictionaries, e.g.
You could use
[result allValues]
if you really need an Array.If you need a sorted array, you need to sort it manually: