How to create a sub NSArray that includes key-value pairs? - ios

I have the following NsArray and I want to sort it and create a sub array that include specific key-value pairs.
{
scores = (
{
category = 2;
"league_code" = epl;
"team_away" = Everton;
"team_home" = Liverpool;
},
{
category = 2;
"league_code" = epl;
"team_away" = Fulham;
"team_home" = "Swansea City";
},
{
category = 3;
"league_code" = ita;
"team_away" = Torino;
"team_home" = Milan;
},
{
category = 3;
"league_code" = ita;
"team_away" = Lazio;
"team_home" = Juve;
}
}
}
and I would like to create a new array or just modify array to include only objects with "league_code" = epl key.
So I want to get
{
scores = (
{
category = 2;
"league_code" = epl;
"team_away" = Everton;
"team_home" = Liverpool;
},
{
category = 2;
"league_code" = epl;
"team_away" = Fulham;
"team_home" = "Swansea City";
}
}
}
I tried to convert it to use dictionaryWithObjects:forKeys but it didn't work.

NSMutableArray* newArray = [NSMutableArray array];
NSArray* oldArray = outerDictionary[#"scores"];
for (NSDictionary* dictEntry in oldArray) {
NSString* leagueCode = dictEntry[#"league_code"];
if ([leagueCode isEqualToString #"epl"]) {
[newArray addObject:dictEntry];
}
}
Was that all that hard?

Loop Through and the if it matches your conditions add it to a dictionary. I recommend the for-loop but any loop while do.

Related

NSDictionary - Get unique records choosing which keys has to be uniques

I have an array of dictionaries with N keys. I want to create an array of unique dicts which contains only some keys.
Example. My dict:
{
"m_anno" = 2017;
"m_c_ultimo" = "4.130";
"m_cod" = 4522;
"m_cod_art" = "*B";
"m_des" = "SCRITTA BIANCA NISSAN";
"m_ditta" = SIS;
"m_prz" = "0.000";
"m_qta" = "1.000";
"m_sconto" = {
};
},
{
"m_anno" = 2017;
"m_c_ultimo" = "25.020";
"m_cod" = 4522;
"m_cod_art" = "000/01200";
"m_des" = "CABLAGGIO X TIMONE";
"m_ditta" = SIS;
"m_prz" = "0.000";
"m_qta" = "1.000";
"m_sconto" = {
};
},
{
"m_anno" = 2017;
"m_c_ultimo" = "1.000";
"m_cod" = 4523;
"m_cod_art" = 000000;
"m_des" = "BLISTER O-RING 3106";
"m_ditta" = SIS;
"m_prz" = "0.000";
"m_qta" = "1.000";
"m_sconto" = {
};
},
I want to get unique values of m_anno and m_cod keys. Expected result:
{
{
"m_anno" = 2017
"m_cod" = 4522
}
{
"m_anno" = 2017
"m_cod" = 4523
}
}
Which is the simplest way?
Basically you have to iterate over the array (quelle surprise!) and put it in a collection, if the pair doesn't exist yet. The second task can be accomplished by using an instance of NSSet or NSOrderedSet depending on the requirement that the order has to be preserved:
NSArray *values = …; // You start with this
NSMutableOrderedSet *uniquePairs = [NSMutableOrderedSet new];
for( NSDictionary *value in values )
{
NSDictionary *pair = #{ #"m_anno":[value objectForKey:#"m_anno"], #"m_cod":[value objectForKey:#"m_cod"] }; // Create smaller version
[uniquePairs addObject:pair];
}
There might be a more elegant way. (Depends of the point of view)
Create an addition to dictionaries, that reduces the array to the desired keys:
NSDictionary( UnifyAnnoAndCodeAddition )
- (NSDictionary*)annoAndCod
{
return #{ #"m_anno":[self objectForkey:#"m_anno"], #"m_cod":[self objectForKey:#"m_code"]};
}
Then use key-value coding to create an array of the reduced dictionaries and make a set of this:
NSArray *values = …; // You start with this
NSArray *pairs = [values valueForKey:#"annoAndCod"];
NSOrderedSet = [NSOrderedSet orderedSetWithArray:pairs];
Well, at least it is shorter.

distinctUnionOfObjects changes the order of an array

Below is my original array :
{
FilePath = "Selfcare.jpg";
ModuleId = 18;
ModuleName = "Infant N Toddler";
SkillLevelID = 59;
SkillLevelName = "Self Care";
},
{
FilePath = "Preschool.jpg";
ModuleId = 18;
ModuleName = "Infant N Toddler";
SkillLevelID = 60;
SkillLevelName = "Preschool Readiness";
},
{
FilePath = "Learning_Primary.jpg";
ModuleId = 22;
ModuleName = Cognitive;
SkillLevelID = 71;
SkillLevelName = "Learning Readiness - Primary Skills";
},
{
FilePath = "PreAcad_Primary.jpg";
ModuleId = 22;
ModuleName = Cognitive;
SkillLevelID = 72;
SkillLevelName = "Pre-Academics: Primary Skills";
}
when I apply distinctUnionOfObjects
NSArray *curriculums = [array valueForKeyPath:#"#distinctUnionOfObjects.ModuleName"];
this changes the order giving me resulting array
<__NSArrayI>(
Cognitive,
Infant N Toddler
)
It should give
<__NSArrayI>(
Infant N Toddler,
Cognitive
)
as per original array order.
How do I restrict this order change?
please try this one
NSArray *orderedSet = [[NSOrderedSet orderedSetWithArray:[people valueForKey:#"ModuleName"]] array];

I am filtering a multilevel NSArray using NSPredicate., i am trying to filter 3rd child of array using predicate but i am getting this

Unable to parse the format string "json.option_titles.ANY.options.ANY.jobID == %#
Although i can use the for loop but i might have option titles length long so it will be not good. will it be possible using nspredicate?
This is my sample Data
(
{
dept = 1194;
id = 2299;
job = 22048;
json = {
name = tester;
"option_titles" = (
{
"custom_option_title" = "";
"financing_option" = "";
options = (
{
hours = "2.00";
jobID = 22048;
optionDesc = "Sample Description";
},
{
hours = "2.00";
jobID = 22048;
optionDesc = "Sample Description";
},
);
}
);
"system_observations" = "";
};
name = tester;
"sort_order" = 178;
"system_observations" = "";
},
{
dept = 1195;
id = 2300;
job = 22000;
json = {
name = tester second;
"option_titles" = (
{
"custom_option_title" = "title option";
"financing_option" = "";
options = (
{
hours = "2.00";
jobID = 22000;
optionDesc = "Sample Description";
},
{
hours = "2.00";
jobID = 22000;
optionDesc = "Sample Description";
},
);
}
);
"system_observations" = "";
};
name = tester;
"sort_order" = 179;
"system_observations" = "";
}
)
Tried Code:-
NSArray *allJobs = [self getAllJobs];
allJobs = [allJobs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(dept_id == %#)",deptId]];
NSMutableArray *coumpoArray = [NSMutableArray new];
for (NSDictionary *job in allJobs) {
NSPredicate *predicateDeepFilterJobID = [NSPredicate predicateWithFormat:#"json.option_titles.options.jobID == %#",job[#"id" ]];
[coumpoArray addObject:predicateDeepFilterJobID];
}
NSPredicate *pr = [NSCompoundPredicate orPredicateWithSubpredicates:coumpoArray];
filterBydept = [arrayTemplate filteredArrayUsingPredicate:pr];
Tried another predicate:-
NSArray *allJobs = [self getAllJobs];
allJobs = [allJobs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(dept_id == %#)",deptId]];
NSMutableArray *coumpoArray = [NSMutableArray new];
for (NSDictionary *job in allJobs) {
NSPredicate *predicateDeepFilterJobID = [NSPredicate predicateWithFormat:#"json.option_titles.ANY.options.ANY.jobID == %#",job[#"id" ]];
[coumpoArray addObject:predicateDeepFilterJobID];
}
NSPredicate *pr = [NSCompoundPredicate orPredicateWithSubpredicates:coumpoArray];
filterBydept = [arrayTemplate filteredArrayUsingPredicate:pr];

Filter NSMutableArray with All the values of nsarray

I have MutableArray like this...
restaurants = ({
cuisines = ({
"cuisine_id" = 1;
"cuisine_name" = Indian;
},
{
"cuisine_id" = 2;
"cuisine_name" = SriLanka;
}
);}
{ cuisines = ({
"cuisine_id" = 1;
"cuisine_name" = Chinese;
},
{
"cuisine_id" = 2;
"cuisine_name" = Afghani;
}
);}
{cuisines =({
"cuisine_id" = 1;
"cuisine_name" = Chinese;
},
{
"cuisine_id" = 2;
"cuisine_name" = Afghani;
}
);}
)
And I'm Filtering Restaurants Array With multiple values of cuisine_name
For Example if I have a,
Nsarray like this cuisine_name (
Indian,
Srilankan,
Chinese,
)
I want to filter my Restaurants array on basis of each object of cusine_name.
At present I'm doing like this..
NSPredicate *predicateCuisines = [NSPredicate predicateWithFormat:#"(cuisines.cuisine_name = %#)",[cuisineTypes valueForKey:#"cuisine_name"]];
[self.arrRestaurantList filterUsingPredicate:predicateCuisines];
But it filtering Using description...For Restaurant Array which contains whole three values(Indian,Srilankan,Chinese) but i want to filter with each object of cuisine_name.
Any help will really appreciated..
plz use this
NSArray* arrtu4 = #[#{#"cuisines" : #[#{#"cuisine_id" : #1,#"cuisine_name" : #"Indian"},#{ #"cuisine_id" : #2, #"cuisine_name" : #"SriLanka"}]},#{ #"cuisines" : #[#{#"cuisine_id" : #1,#"cuisine_name" : #"Chinese"},#{#"cuisine_id" : #2,#"cuisine_name" : #"Afghani"}]},#{#"cuisines" :#[#{#"cuisine_id" :#1,#"cuisine_name" : #"Chinese"},#{ #"cuisine_id" : #2,#"cuisine_name" : #"Afghani"}]}];
NSMutableArray *arrryfilted = [NSMutableArray array];
NSArray *arrayCountrys = #[#"Chinese",#"SriLanka",#"Indian"];
for (int i = 0; i<arrtu4.count; i++)
{
NSArray *filterArray2 = [[arrtu4 objectAtIndex:i]valueForKey:#"cuisines"];
NSArray *filterArray3 = [filterArray2 filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
return [arrayCountrys containsObject:[evaluatedObject valueForKey:#"cuisine_name"]] ;
}]];
[arrryfilted addObjectsFromArray:filterArray3 ];
}
NSLog(#"%#",arrryfilted);
output:
2016-08-20 16:44:59.856 coredataReltaion[6762:152672] (
{
"cuisine_id" = 1;
"cuisine_name" = Indian;
},
{
"cuisine_id" = 2;
"cuisine_name" = SriLanka;
},
{
"cuisine_id" = 1;
"cuisine_name" = Chinese;
},
{
"cuisine_id" = 1;
"cuisine_name" = Chinese;
}
)

iOS NSArray Sorting

I have a nested array and want to sort it by a key present inside the inner array.
below given is my array which I want to sort using NSSortDescriptor or in other way.
fares(
{
pid = 1;
type1 = (
{
color = "red";
size = "big";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
});
type2 = (
{
color = "green";
size = "small";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
})
}
{
pid = 1;
type1 = (
{
color = "red";
size = "big";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
});
type2 = (
{
color = "green";
size = "big";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
})
})
How can i sort above array using key "type2->properties->payment"?
-------update-----------
I modified the array and used NSSortDescriptor which solved my problem
Try this:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"type1.size" ascending:YES];
NSArray *finalArray = [self.firstArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
Try this by inputing the fares array into this method-
+(NSArray*)sortedListBySize:(NSArray*)_unsortedList{
NSArray *sortedListBySize = [_unsortedList sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2){
if ([[obj1 valueForKeyPath:#"type2.properties.payments" ] intValue] < [[obj1 valueForKeyPath:#"type2.properties.payments"] intValue]) {
return NSOrderedAscending;
} else if ([[obj1 valueForKeyPath:#"type2.properties.payments" ] intValue] > [[obj1 valueForKeyPath:#"type2.properties.payments"] intValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}];
return sortedListBySize;
}

Resources