Tarvo Mäesepp
Tarvo Mäesepp

Reputation: 4533

Add key and value to all childs in JSON tree in Firebase

I want to add key and value to all childs in Firebase("rate":0).

This is my JSON tree. How I am able to loop trough the JSON tree and set "rate":0 to all of them like this:

enter image description here

I tried doing it with Pyrebase but it was a pain.

Upvotes: 0

Views: 337

Answers (1)

Dravidian
Dravidian

Reputation: 9945

Try:-

  FIRDatabase.database().reference().child("Snuses").observeSingleEvent(of: .value, with: {(toBeAppendedSnap) in


        if let snapDict = toBeAppendedSnap.value as? [String:AnyObject]{

            for each in snapDict{

                let eachKey = each.key

                if let eachValue = each.value as? NSMutableDictionary{

                     eachValue.setObject("0", forKey: "rate" as NSCopying)
                     FIRDatabase.database().reference().child("Snuses/\(eachKey)").setValue(eachValue, withCompletionBlock: { (err, ref) in
                        print("Updated")
                     })
                }
            }
        }
    })

Or:-

    FIRDatabase.database().reference().child("Snuses").observeSingleEvent(of: .value, with: {(toBeAppendedSnap) in


        if let snapDict = toBeAppendedSnap.value as? [String:AnyObject]{

            for each in snapDict{

                FIRDatabase.database().reference().child("Snuses/\(each.key)").updateChildValues(["rate" : "0"])

            }
        }
    })

Upvotes: 1

Related Questions