Get index of object from array of dictionary with key value - ios

I have one array with dictionary.
Now i want to get index number of object with particular key value.
Like key = "xyz" and value = "abc".
I need index of object having above matching in dictionary.
{
Id = 20085;
IsNew = 1;
Title = Circular;
},
{
Id = 20088;
IsNew = 0;
Title = Query;
},
{
Id = 20099;
IsNew = 1;
Title = Blog;
},
{
Id = 20104;
IsNew = 1;
Title = News;
},
{
Id = 20172;
IsNew = 1;
Title = AssignTask;
},
{
Id = 20183;
IsNew = 1;
Title = Gallery;
},
{
Id = 20204;
IsNew = 1;
Title = Poll;
},
{
Id = 20093;
IsNew = 1;
Title = Assignment;
},
{
Id = 20209;
IsNew = 1;
Title = Activity;
},
{
Id = 20130;
IsNew = 1;
Title = Behaviour;
},
{
Id = 20180;
IsNew = 1;
Title = Result;
}
now i need index of object with having key = "Title" and value = "result"

You can use indexOf(_:) for this:
let index = array.indexOf{ $0["key"] == value }
In Swift 3.0, it's been renamed to index(Where:):
let index = array.index{ $0["key"] == value }
You can see this in action here.

Here is what you should be doing after using a json parser
let array:NSArray = [
[
"Id": 20130,
"IsNew": 1,
"Title":"Behaviour"
],
[
"Id": 20180,
"IsNew": 1,
"Title":"Result"
]]
let k = array as Array
let index = k.indexOf {
if let dic = $0 as? Dictionary<String,AnyObject> {
if let value = dic["Title"] as? String
where value == "Result"{
return true
}
}
return false
}
print(index) // index

I'd start with mapping the id values to an array, then getting the index of the id you're looking for.
func getIndexOf(itemID: Int) -> Int {
//Map out all the ids from the array of dictionaries into an array of Integers
let keysArray = dictionaries.map { (dictionary) -> Int in
return dictionary.value(forKey: "Id")
}
//Find the index of the id you passed to the functions
return keysArray.index(of: itemID)
}

other mainstream way to do this
func getIndex(of key: String, for value: String, in dictionary : [[String: Any]]) -> Int{
var count = 0
for dictElement in dictionary{
if dictElement.keys.contains(key) && dictElement[key] as! String == value{
return count
}
else{
count = count + 1
}
}
return -1
}
var sampleDict : [[String:Any]] = [
[
"Id" : 20130,
"IsNew" : 1,
"Title" : "Behaviour"
],
[
"Id" : 20130,
"IsNew" : 1,
"Title" : "Result"
],
]
let index = getIndex(of: "Title", for: "Result", in: sampleDict)
print(index)
This will print 1.

This answer is for the Swift 5.2 and above versions.
arr.append(["Title":titleName,"ID":1,"Result":true])
arr.append(["Title":titleName,"ID":2,"Result":true])
arr.append(["Title":titleName,"ID":3,"Result":true])
arr.append(["Title":titleName,"ID":4,"Result":true])
This is an array of dictionary format. And if you want to find an index of an object where ID == 3
func findIndex(Id : Int ) -> Int? {
guard let index = arr.firstIndex(where: {
if let dic = $0 as? Dictionary<String,AnyObject> {
if let value = dic["ID"] as? Int, value == Id {
return true
}
}
return false
}) else { return nil }
return index
}
let myIndex = findIndex(3)
self.arr.insert( ["Title":titleName,"ID":10,"Result":true]) at: myIndex)

Related

sort array of anyobject Swift 3

I am trying to sort an array of anyobject, but not able to do it.I get some data from Parse database in AnyObject format. As per below data, I want to sort this AnyObject array by "NAME". Below is my code -
let sortedArray = (myArray as! [AnyObject]).sorted(by: { (dictOne, dictTwo) -> Bool in
let d1 = dictOne["NAME"]! as AnyObject; // this line gives error "Ambiguous use of subscript"
let d2 = dictTwo["NAME"]! as AnyObject; // this line gives error "Ambiguous use of subscript"
return d1 < d2
})
myArray looks like this -
{
LINK = "www.xxx.com";
MENU = Role;
"MENU_ID" = 1;
NAME = "A Name";
SUBMENU = "XXX";
"Training_ID" = 2;
},
{
LINK = "www.xyz.com";
MENU = Role;
"MENU_ID" = 2;
NAME = "B name";
SUBMENU = "jhjh";
"Training_ID" = 6;
},
{
LINK = "www.hhh.com";
MENU = Role;
"MENU_ID" = 3;
NAME = "T name";
SUBMENU = "kasha";
"Training_ID" = 7;
},
{
LINK = "www.kadjk.com";
MENU = Role;
"MENU_ID" = 5;
NAME = "V name";
SUBMENU = "ksdj";
"Training_ID" = 1;
},
{
LINK = "www.ggg.com";
MENU = Role;
"MENU_ID" = 4;
NAME = "K name";
SUBMENU = "idiot";
"Training_ID" = 8;
},
{
LINK = "www.kkk.com";
MENU = Role;
"MENU_ID" = 6;
NAME = "s name";
SUBMENU = "BOM/ABOM/BSM";
"Training_ID" = 12;
}
Any help would be much appreciated. Thanks!
It's not [AnyObject] (array of I-have-no-idea), it's array of dictionaries [[String:Any]]. Be more specific, this resolves the error.
In Swift 3 the compiler must know the specific type of all subscripted objects.
let sortedArray = (myArray as! [[String:Any]]).sorted(by: { (dictOne, dictTwo) -> Bool in
let d1 = dictOne["NAME"]! as String
let d2 = dictTwo["NAME"]! as String
return d1 < d2
})
Why are converting array to [AnyObject] instead of that convert the array to the [[String:Any]] means Array of Dictionary and tell the compiler that array contains Dictionary as objects.
if let array = myArray as? [[String:Any]] {
let sortedArray = array.sorted(by: { $0["NAME"] as! String < $1["NAME"] as! String })
}
Note: As of you are having NAME key with String value in your each dictionaries of array I have force wrapped it with the subscript.
You can use below function if you want
//function to sort requests
func sortRequests(dataToSort: [[String:Any]]) -> [[String:Any]] {
print("i am sorting the requests...")
var returnData = [[String:Any]]()
returnData = dataToSort
returnData.sort{
let created_date0 = $0["date"] as? Double ?? 0.0
let created_date1 = $1["date"] as? Double ?? 0.0
return created_date0 > created_date1
}
return returnData
}

Swift 3: Accessing nested dictionary from returns nil?

I'm having a problem trying to access a nested Dictionary, which seems to return nil.
Here's the output my info of type Dictionary<String, Any>:
info = ["list_order": 1, "name": Some Text, "id": 1, "menu_items": {
1 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "2.00";
};
2 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "5.00";
id = 2;
};
}]
The output of info["menu_items"]:
info["menu_items"] = {
1 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "2.00";
id = 1;
};
2 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "5.00";
id = 2;
};
}
However, the following assigning produces a nil in test:
let test = info["menu_items"] as? Dictionary<Int, Any>
Is there something not obvious or am I not understanding basic fundamentals?
If your key is not Int type then most probably it is of String type, try once using [String: Any].
if let menuItems = info["menu_items"] as? [String: Any] {
print(menuItems)
}

Get the index out of AnyObject list of items IOS

parsed is an NsDictionary and I am pulling the balances out of it via
if let findbalances: AnyObject = parsed["balances"]
which gives me a list of balances in AnyObject format
(
{
"available_amount" = 133519;
currency = AUD;
},
{
"available_amount" = 7854;
currency = CAD;
},
{
"available_amount" = 88581;
currency = EUR;
},
{
"available_amount" = 0;
currency = GBP;
},
{
"available_amount" = 63618;
currency = INR;
},
{
"available_amount" = 375;
currency = NZD;
},
{
"available_amount" = 0;
currency = TRY;
},
{
"available_amount" = 2918958;
currency = USD;
}
)
I know that
let whatCurrency = (findbalances[7]["currency"] as! String)
=USD But how do I find that value [7] if the amount of objects changes?
I want to match on USD
I tried
let defaultcurr = "USD"
let findUSD = findbalances.indexOfObject(defaultcurr)
but that gave me 9223372036854775807
How do I just find 7
9223372036854775807 is NSNotFound.
You can use a closure as argument of indexOf
let defaultcurr = "USD"
let findUSDIndex = findbalances.indexOf { ($0["currency"] as! String) == defaultcurr }
Or you can filter the entire row
let findUSD = findbalances.filter { ($0["currency"] as! String) == defaultcurr }.first
indexOfObject seems to be using NSArray. Don't do that. Use Swift native Array and cast your collection object to [[String:AnyObject]] :
if let findbalances = parsed["balances"] as? [[String:AnyObject]] { ...

How to get dictionary objects in array

I have a dict(NSDictionary) that has the following data.
{
images = (
{
image = "image.jpg";
scores = (
{
"classifier_id" = "Adventure_Sport";
name = "Adventure_Sport";
score = "0.662678";
},
{
"classifier_id" = Climbing;
name = Climbing;
score = "0.639987";
},
{
"classifier_id" = Flower;
name = Flower;
score = "0.628092";
},
{
"classifier_id" = "Nature_Scene";
name = "Nature_Scene";
score = "0.627548";
},
{
"classifier_id" = Icicles;
name = Icicles;
score = "0.617094";
},
{
"classifier_id" = Volcano;
name = Volcano;
score = "0.604928";
},
{
"classifier_id" = Potatoes;
name = Potatoes;
score = "0.602799";
},
{
"classifier_id" = "Engine_Room";
name = "Engine_Room";
score = "0.595812";
},
{
"classifier_id" = Bobsledding;
name = Bobsledding;
score = "0.592521";
},
{
"classifier_id" = White;
name = White;
score = "0.587923";
},
{
"classifier_id" = Yellow;
name = Yellow;
score = "0.574398";
},
{
"classifier_id" = "Natural_Activity";
name = "Natural_Activity";
score = "0.54574";
},
{
"classifier_id" = Butterfly;
name = Butterfly;
score = "0.526803";
},
{
"classifier_id" = "Dish_Washer";
name = "Dish_Washer";
score = "0.513662";
},
{
"classifier_id" = Rainbow;
name = Rainbow;
score = "0.511032";
}
);
}
);
}
I am not able to figure out a way to access classfier_id in an array
Really need your help. Thanks. PS I have already tried dict["scores"] and dict["image.scores"]
Kindly help.. Thanks
You want
let classifier_ids = dict["scores"].map{$0["classifier_id"]}
If your containers are NSObjects rather than Swift Dictionaries and Arrays then you will need to add some type-casting, but that's the basic idea.
This code would be safer for non-typed collections:
var classifier_ids: [String?]
if let array = dict["scores"] as? [String:String]
{
let classifier_ids = array.map{$0["classifier_id"]}
}
That should give you an array of optionals, where a given entry will be nil if that entry in the array did not contain a "classifier_id" key/value pair.
Or if you want to skip entries that don't contain a "classifier_id" key/value pair:
var classifier_ids: [String]
if let array = dict["scores"] as? [String:String]
{
let classifier_ids = array.flatmap{$0["classifier_id"]}
}
Taking it a step at at time:
if let array = dict["images"] as? NSArray {
if let array2 = array[0]["scores"] as? NSArray {
if let ids = array2.valueForKey("classifier_id") as? [String] {
// use array of ids
print(ids)
}
}
}
or all in one shot:
if let ids = (dict["images"]?[0]["scores"])?.valueForKey("classifier_id") as? [String] {
// use array of ids
print(ids)
}

NIL when Parsing JSON

I am trying to parse and get the values from this structure of JSON:
["mst_customer": 1, "data": {
0 = 2;
1 = 1;
2 = 1;
3 = "JAYSON TAMAYO";
4 = "581-113-113";
5 = 56;
6 = on;
7 = g;
8 = jayson;
9 = active;
"app_access" = on;
id = 2;
"mst_customer" = 1;
name = "Jayson Tamayo";
status = active;
territory = 1;
}, "status": OK, "staff_id": 2, "staff_name": Jayson Tamayo]
I use the following Swift code to get the values:
(data: Dictionary<String, AnyObject>, error: String?) -> Void in
if error != nil {
print(error)
} else {
if let feed = data["data"] as? NSDictionary ,let entries = data["data"] as? NSArray{
for elem: AnyObject in entries{
if let staff_name = elem["name"] as? String{
print(staff_name)
}
}
}
}
I am trying to get the name by using the keys name or staff_name. But I always get nil.
you want to access staff_name, which is not in "data" variable ... you can simply get that like
if error != nil {
print(error)
} else {
if let name = data["staff_name"] as? String{
print(name)
}
}
for elem: AnyObject in entries{
if let songName = elem["name"] as? String{
print(songName)
}
}
//replace above code with below code
if let songName : String = entries["name"] as? String{
print(songName)
}

Resources