How to get Date Value from array? - ios

I want to store the date in a separate array…..How to do this???Am getting confused….Pls help me….
(
{
"2015-03-27" = {
amount = 13086;
date = "2015-03-26 18:30:00 +0000";
"date-day" = 27;
"date-month" = Mar;
"date-year" = 2015;
units = 2160;
};
},
{
"2015-08-03" = {
amount = 18300;
date = "2015-08-02 18:30:00 +0000";
"date-day" = 03;
"date-month" = Aug;
"date-year" = 2015;
units = 2950;
};
},
)

Your data is in Array (which is collection of Dictionary)
So, first get Dictionary from Array & then add key of particular dictionary in to new Array (which is resulted array of Dates)
Try this:
NSArray *arrData;
NSMutableArray *arrDates = [NSMutableArray array];
for (NSDictionary *dict in arrData) {
[arrDates addObject:[[dict allKeys] firstObject]];
}
NSLog(#"Dates :: %#", arrDates);

The outer object is an array, item 0 contains the two dictionaries.
NSDictionary *dictionary = array[0];
Then enumerate the dictionary and extract the date values
NSMutableArray *dates = [NSMutableArray array];
for (NSString *key in dictionary) {
[dates addObject: dictionary[key][#"date"]];
}

Related

How to retrieve NSStrings stored in multiple NSArrays inside of an NSArray

I'm building an "invite friends" feature.
It's already working I just have one issue I'm wrestling with.
I'm retrieving my contact list, and every time I select a contact I'm adding them to a NSMutableArray which I'm calling "selectedUser".
So each item in the NSMutableArray at this point are "Dictionaries" and some of the values are "Dictionaries" as well. Especially the "phones" key I'm trying to access and retrieve the value key.
What I'm trying to accomplish is to only retrieve the "phone numbers" in strings stored them inside a NSArray that I can then past to [messageController setRecipients:recipents]; recipents being the array of only NSStrings of phone numbers.
This is my code so far, and what I'm getting is a NSArray with multiple NSArrays in it were each array only has one string being the phone number.
NSArray *titles = [self.selectedUsers valueForKey:#"phones"];
NSArray *value = [titles valueForKey:#"value"];
NSLog(#"Output the value: %#", value);
NSArray *recipents = value;
This is what I get in the log
2016-01-04 12:27:59.721 InviteFriends[4038:1249174] (
(
"(305) 731-7353"
),
(
"(786) 306-2831"
),
(
"(305) 333-3297"
)
)
This is the log of the dictionary itself
{
birthday = "";
company = "";
createdAt = "2015-09-06 16:14:18 +0000";
department = "";
emails = (
);
firstName = "Lola";
firstNamePhonetic = "";
id = 699;
jobTitle = "";
lastName = "";
lastNamePhonetic = "";
middleName = "";
nickName = "";
note = "";
phones = (
{
label = Home;
value = "(305) 503-3957";
}
);
prefix = "";
suffix = "";
updatedAt = "2015-09-23 23:31:25 +0000";
}
)
Thanks
If I am understanding this correctly, on the line where you write
NSArray *value = [titles valueForKey:#"value"];,
You are trying to index the NSArray full of dictionaries using the index "value", which doesn't make sense. You should instead loop through your titles array, pull out the value from each dictionary element, and then append that element to your recipents array.
Here is some sample code that should do what I think you want.
NSArray *titles = [self.selectedUsers valueForKey:#"phones"];
NSMutableArray *recipients = [[NSMutableArray alloc] init];
for (NSDictionary* dict in titles) {
NSString* value = [dict objectForKey:#"value"];
[recipients addObject:value];
}
NSLog(#"Phone Numbers: %#",recipients);
Here is the solution I came up with.
First run a for loop to grab the first key. Then nest another for loop to grab the second key.
NSArray *values = self.selectedUsers;
NSMutableArray *recipients = [[NSMutableArray alloc] init];
NSArray *values = self.selectedUsers;
NSMutableArray *recipients = [[NSMutableArray alloc] init];
for (NSDictionary* dict in values) {
// Grabs phones key
NSDictionary *titles = [dict objectForKey:#"phones"];
for (NSDictionary* dict2 in titles) {
// Grabs the "value" key
NSString* value = [dict2 objectForKey:#"value"];
[recipients addObject:value];
}
}

How to get JSON response array all index values?

I need to get JSON response array all indexes values and maintain separate array. Here below I have posted my JSON response and I wanted to get console output looks like below also. Please help me.
response : [ {
A = [ {
name : "sons";
age = [
4
];
},
{
name : "rondo";
age = [
2
];
},
];
} ]
I need to store separate array separate values looks like below console output
2014-09-18 10:24:39.461 Myapp[1133:60b] RESULT : {
name = "sons";
age = 4;
}
2014-09-18 10:24:39.462 Myapp[1133:60b] RESULT : {
name = "rondo";
age = 2;
}
Here below I tried but I Know I can get only 0th index value but I need to get all index value from JSON response array:
myvalue = [NSString stringWithFormat:#"%#",[[[[responsData objectAtIndex:0] valueForKey:#"A"] objectAtIndex:0] valueForKey:#"name"]];
if you want to get all objects, get the array using the respective key.Then store the result in another array by iterating the for loop according to array count.
NSArray *recordsArr = [[responsedata objectAtIndex:0] valueForKey:#"A"];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [recordsArr count]; i ++) {
NSMutableDictionary *recordDict = [[NSMutableDictionary alloc] init];
[recordDict setObject:[[recordsArr objectAtIndex:i] valueForKey:#"name"] forKey:#"name"];
[recordDict setObject:[[[recordsArr objectAtIndex:i] valueForKey:#"age"] objectAtIndex:0] forKey:#"age"];
[resultArray addObject:recordDict];
}
NSLog(#"%#",resultArray);
output:
2014-09-18 12:49:22.047 testprj[1044:60b] (
{
age = 4;
name = sons;
},
{
age = 2;
name = rondo;
}
)
NSString *strName = (NSString *) [yourArray valueForKey:#"name"];
NSInteger age = [(NSNumber *) [yourArray valueForKey:#"age"] integerValue];

Merge arrays with its count in Objective C

I have an array like this
A = [#"aa",#"cc",#"bb",#"bb",#"cc",#"aa",#"cc"]
I need to convert it to
A = [#"x2 aa",#"x2 bb",#"x3 cc"]
Count the similar elements and create a new string, add it to new array. As shown here:
NSArray *aArray = #[#"aa", #"cc", #"bb", #"bb", #"cc", #"aa", #"cc"];
NSCountedSet *set = [NSCountedSet setWithArray:aArray];
NSMutableArray *countedArray = [NSMutableArray new];
for (NSString *str in set) {
[countedArray addObject:[NSString stringWithFormat:#"x%ld %#",[set countForObject:str], str]];
}
NSLog(#"%#",countedArray);
Output:
(
"x2 bb",
"x2 aa",
"x3 cc" )

how to group array of nsdictionary according to the value inside the element

I have array of dictionary that needs to be grouped according to PO which is part of the element and also get the total of quantityOrdered according to the same PO.
The PO is dynamic it means it can be any value that needs to be filtered and compute the quantityOrderd accordingly.
Please help.
{
PO = PO2;
QuantityReceived = 1;
},
{
PO = PO1;
QuantityReceived = 3;
},
{
PO = PO1;
QuantityReceived = 3;
},
{
PO = PO3;
QuantityReceived = 2;
},
{
PO = PO2;
QuantityReceived = 2;
},
{
PO = PO3;
QuantityReceived = 4;
},
{
PO = PO1;
QuantityReceived = 1;
},
Apology for the confusion or incomplete question but i need to create a new array of dictionary with similar like this :
{
PO = PO1;
TotalQuanityReceived=7;
LineItems=3;
},
{
PO = PO2;
TotalQuanityReceived=3;
LineItems=2;
},
{
PO = PO3;
TotalQuanityReceived=6;
LineItems=2;
},
i updated my example and make it easy to read.
- (NSArray *)whatever:(NSArray *)dictionaries
{
NSMutableArray *results = [[NSMutableArray alloc] init];
NSMutableDictionary *resultsByPO = [[NSMutableDictionary alloc] init];
for (NSDictionary *dictionary in dictionaries) {
id po = [dictionary objectForKey:#"PO"];
NSMutableDictionary *result = [resultsByPO objectForKey:po];
if (result == nil) {
result = [[NSMutableDictionary alloc] init];
[resultsByPO setObject:result forKey:po];
[results addObject:result];
[result setObject:po forKey:#"PO"];
}
double total = [[result objectForKey:#"TotalQuantityReceived"] doubleValue];
total += [[dictionary objectForKey:#"QuantityOrdered"] doubleValue];
int count = 1 + [[result objectForKey:#"Count"] intValue];
[result setObject:#(total) forKey:#"TotalQuantityReceived"];
[result setObject:#(count) forKey:#"Count"];
}
return results;
}
More pain will come with PO values not conforming to NSCopying.
You can do it the clever way with KVC or the stupid easy way. Let's do it the stupid easy way!
Make an empty NSMutableDictionary. Let's call it dict.
Cycle through your array of dictionaries. For each dictionary:
Fetch its PO. Call that value thisPO.
Fetch dict[thisPO]. Was it nil?
a. Yes. Okay, so this particular PO has not yet been encountered. Set dict[thisPO] to this dictionary's quantity received (as an NSNumber).
b. No. Turn that value into an integer, add this dictionary's quantity received, and set the total back into dict[thisPO] (as an NSNumber).
Done! The result is not quite what you asked for; the result looks like this:
{
PO1 = 100;
PO2 = 120;
...
}
But now, you see, the work of totalling is done and it is easy to transform that into an array of dictionaries if that is what you want.
Not 100% sure if this is what you are saying or not, but to sort an array of dictionaries based on one of the elements it would look something like this.
NSDictionary *d1 = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithDouble:100],#"PO",
[NSNumber numberWithDouble:0], #"Category",
nil];
NSDictionary *d2 = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithDouble:50],#"PO",
[NSNumber numberWithDouble:90], #"Category",
nil];
NSArray *unsorted = #[d1, d2];
NSArray *sortedArray;
sortedArray = [unsorted sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDictionary *first = (NSDictionary*)a;
NSDictionary *second = (NSDictionary*)b;
NSNumber *firstPO = [first objectForKey:#"PO"];
NSNumber *secondPO = [second objectForKey:#"PO"];
return [firstPO compare:secondPO];
}];
NSLog(#"unsorted = %#", unsorted);
NSLog(#"sorted = %#", sortedArray);
I wasn't really sure what PO was, so I just used an NSNumber as an example. Look at this page for an overview of how you would compare a customer object. http://nshipster.com/nssortdescriptor/.
Then you can loop through the array, now in the correct order and build your next NSDictionary.

Accessing an array with nested objects and displaying keys values

I have this data set here: https://gist.github.com/ryancoughlin/8043604 - If you see tide.tideSummary it contains an array but inside, it contains multiple dictionaries. I am trying access and display tide.tideSummary.date.pretty and display (all 33 of them) in some type of table (but that I have working with dummy data).
I was going through a somewhat similar question here: Keypath for first element in embedded NSArray
Having some trouble finding a solution to access those nested values. Been through plenty of tutorials and posts here on StackOverflow that deal with very basic JSON strings and those work great for me.
UPDATE:
Came across this question: Parsing nested JSON objects with JSON Framework for Objective-C
In my case, I have the following:
NSArray *prettyDate = [[tide objectForKey:#"tideSummary"] valueForKey:#"date"];
prettyDate prints this from NSLog
Pretty date array: (
{
epoch = 1388388109;
hour = 02;
mday = 30;
min = 21;
mon = 12;
pretty = "2:21 AM EST on December 30, 2013";
tzname = "America/New_York";
year = 2013;
},
{
epoch = 1388397506;
hour = 04;
mday = 30;
min = 58;
mon = 12;
pretty = "4:58 AM EST on December 30, 2013";
tzname = "America/New_York";
year = 2013;
},
{
epoch = 1388405656;
hour = 07;
mday = 30;
min = 14;
mon = 12;
pretty = "7:14 AM EST on December 30, 2013";
tzname = "America/New_York";
year = 2013;
}
Then I would be able to loop through each, grab the object and display?
Would I do something like:
Grab parent item tideSummary - array
Grab the item above and store date - dictionary
Access pretty via objectForKey
I have this initWithDict
-(id)initWithDict:(NSDictionary *)json {
self = [super init];
if(self) {
NSDictionary *tide = [json valueForKeyPath:#"tide"];
NSArray *arrOfTideSummaryStats = [json valueForKeyPath:#"tide.tideSummaryStats"];
NSDictionary *dctOfTideSummaryStats = [arrOfTideSummaryStats objectAtIndex:0];
NSArray *arrOfTideSummary = [json valueForKeyPath:#"tide.tideSummary"];
// Loop through the date then...
// Loop and grab 'pretty'
// The "first" is the from the example link in my question above. Experimental oonly
id pretty = [arrOfTideSummary valueForKeyPath: #"#first.tideSummary.date.pretty"];
// This all works below
self.maxheight = [NSString stringWithFormat:#"%#", [dctOfTideSummaryStats valueForKey: #"maxheight"]];
self.minheight = [NSString stringWithFormat:#"%#", [dctOfTideSummaryStats valueForKey: #"minheight"]];
/*============================================================*/
NSArray *arrOfTideInfo = [json valueForKeyPath:#"tide.tideInfo"];
NSDictionary *dctOfTideInfo = [arrOfTideInfo objectAtIndex:0];
self.tideSite = [dctOfTideInfo valueForKey:#"tideSite"];
}
return self;
}
Does anyone have any examples or a direction to steer me in? Would love a resource or question to work off of.
-(void)parseJson:(id)json{
NSDictionary *tide = [json objectForKey:#"tide"];
NSArray *tideSummary = [tide objectForKey:#"tideSummary"];
for (int i = 0; i < tideSummary.count; i++) {
NSDictionary *eachTideSummary = [tideSummary objectAtIndex:i];
NSDictionary *dateDic = [eachTideSummary objectForKey:#"date"];
NSDictionary *utcdateDic = [eachTideSummary objectForKey:#"utcdate"];
NSLog(#"Preety from date dictionary: %#", [dateDic objectForKey:#"pretty"]);
NSLog(#"Preety from utcdate dictionary: %#", [utcdateDic objectForKey:#"pretty"]);
}
}
You can take a look at Initialize NSArray with data from NSdictionary as I have already answered this
Hope this helps.
If I'm understanding what you are trying to do, you should be able to replace this part:
// Loop through the date then...
// Loop and grab 'pretty'
with something like:
for (NSDictionary *tideSummary in arrOfTideSummary) {
NSDictionary *date = [tideSummary valueForKey:#"date"];
NSLog(#"Pretty date: %#", [date valueForKey:#"pretty"]);
}
If you want the date values in a table of some sort, then you could store them into a new array or some other data structure and then create a table view that uses that as its data source.
I have below data on JSON link...
{
"results":[
{
"address_components": [
{
"long_name": "Satadhar",
"short_name": "Satadhar",
"types":[
"point_of_interest",
"establishment"
]
} ]
]
I fetched data through ASIHTTPREQUEST so the code is below given
-(void)requestFinished:(ASIHTTPRequest *)request {
NSError *err;
NSData *data=[request responseData];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
arr=[[dict valueForKey:#"results"]valueForKey:#"address_components"]; //to fetch the data till inside Starting point i.e address_component
_arrTable=[[NSMutableArray alloc]init]; //take a array to store the data of the index 0 [index 0 store the whole data that is start from [array] ]
_arrTable =[arr objectAtIndex:0]; //get the data of 0th index
NSLog(#" whole data%#",_arrTable);//print it u will get the idea
NSLog(#" my %#",[[arr objectAtIndex:0] valueForKey:#"long_name"]);
NSLog(#" my %#",[[arr objectAtIndex:0] valueForKey:#"short_name"]);
[self.tblview reloadData];
}

Resources