在单个数组中转换字典数组
Convert Array of Dictionary in single Array
此代码:
server_response = [{id:1},{id:2},{id:3},{id:4}]
我现在收到来自服务器的以上响应我只想要一个数组中的 ID 列表,例如
ids = [1,2,3,4];
我知道我们可以通过 for 循环来完成,但是如果响应数组中有数千个 id,则需要很长时间。
有没有更好的方法来实现上面的等式?
NSMutableArray *resultArray = [NSMutableArray array];
for (NSDictionary *dict in server_response) {
[resultArray addObject:[dict objectForKey:@"id"]];
}
试试上面的代码。希望它能帮助你。结果数组有最终值
NSArray *server_response = @[@{@"id":@"1"},@{@"id":@"2"},@{@"id":@"3"},@{@"id":@"4"}];
NSMutableArray *resultArray = [NSMutableArray array];
NSString *birdtemp;
for (NSDictionary *object in server_response) {
birdtemp = object[@"id"];
[resultArray addObject:birdtemp];
}
NSLog(@"%@",resultArray);
输出:[
1、
2、
3、
4个
]
NSArray *result = [yourArray valueForKey:@"id"]
来自 NSArray 实例方法的文档valueForKey:
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects
此代码:
server_response = [{id:1},{id:2},{id:3},{id:4}]
我现在收到来自服务器的以上响应我只想要一个数组中的 ID 列表,例如
ids = [1,2,3,4];
我知道我们可以通过 for 循环来完成,但是如果响应数组中有数千个 id,则需要很长时间。
有没有更好的方法来实现上面的等式?
NSMutableArray *resultArray = [NSMutableArray array];
for (NSDictionary *dict in server_response) {
[resultArray addObject:[dict objectForKey:@"id"]];
}
试试上面的代码。希望它能帮助你。结果数组有最终值
NSArray *server_response = @[@{@"id":@"1"},@{@"id":@"2"},@{@"id":@"3"},@{@"id":@"4"}];
NSMutableArray *resultArray = [NSMutableArray array];
NSString *birdtemp;
for (NSDictionary *object in server_response) {
birdtemp = object[@"id"];
[resultArray addObject:birdtemp];
}
NSLog(@"%@",resultArray);
输出:[ 1、 2、 3、 4个 ]
NSArray *result = [yourArray valueForKey:@"id"]
来自 NSArray 实例方法的文档valueForKey:
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects