Charles Jr
Charles Jr

Reputation: 9149

How to group Firebase NSDictionary items by array count in Swift?

I'm saving a Firebase branch like Users --> Fruit --> "oranges". What I would like is to search through all my "Users" and rank actual fruit i.e 10 Users fruit is Oranges, 8 users fruit is Apples, 12 Users fruit is Grapes. I want to list these in a tableview as Grapes then Oranges then Apples. How can I achieve this either through NSDictionary Methods or Firebase?

Upvotes: 0

Views: 130

Answers (1)

Jiacai Lau
Jiacai Lau

Reputation: 72

Hi I personally think a better way would be to save 2 separate JSON tree,

1) Users --> Fruit --> "Oranges"

2) Fruit --> "Oranges" --> Users

by maintaining 2 JSON trees, you can easily get the number of users for each fruit, the names of all the users who chose that particular fruit and the fruit that each user choose.

It is easy to implement as well, according to the Firebase database documentation,

let key = ref.child("posts").childByAutoId().key
let post = ["uid": userID,
        "author": username,
        "title": title,
        "body": body]
let childUpdates = ["/posts/\(key)": post,
                "/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)

you can easily create 2 JSON tree with a single save.

Upvotes: 1

Related Questions