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

我与影子孤独终老i 提交于 2019-12-25 07:15:21

问题


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:

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


回答1:


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"])

            }
        }
    })


来源:https://stackoverflow.com/questions/39834402/add-key-and-value-to-all-childs-in-json-tree-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!