0

I've local json file, which contains array of dictionaries. I want to group based on key name from below json. Means same name in one group. Please tell me how can I achieve that. Thank you.

Json Data:

[ { "name": "Abc", "number": 123, "marks": 78 }, { "name": "xyz", "number": 456, "marks": 50 }, { "name": "Abc", "number": 789, "marks": 78 } ]

Code:

code and error message

1 Answers1

3

init(grouping:by:)

You should return value of name key in the closure.

 let arr = [ [ "name": "Abc", "number": 123, "marks": 78 ], [ "name": "xyz", "number": 456, "marks": 50 ], [ "name": "Abc", "number": 789, "marks": 78 ] ]
 let dict = Dictionary(grouping: arr) { $0["name"] as! String }
 print(dict)

//["Abc": [["name": "Abc", "number": 123, "marks": 78], ["name": "Abc", "number": 789, "marks": 78]], "xyz": [["name": "xyz", "number": 456, "marks": 50]]]
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
  • I did same. I am getting error. What is wrong in my code? Can you please identify. – user3516627 Jun 13 '18 at 15:57
  • @user3516627 Declare the real dictionary type of the content of your array, not `Any`, and this solution will work. – Eric Aya Jun 13 '18 at 16:19
  • I am not able to pull data from that. I mean how can I pull values from each collection ("Abc" and "xyz") and operate on the members of that particular group and store it at one place in array or something like this. – user3516627 Jun 15 '18 at 17:35