Reputation: 2582
I currently have a JSON object that is structured like this:
"users": {
"0":
{
"items_list": {
"0": [1],
"1": [2,3],
"2": [8, 9, 10],
"3": [11, 12, 13]
},
"name": "Dana"
}
},
Upon pressing a button in a React-Native app, I want to add a value to the array of attributes stored for one of the keys in the items_list.
Specific example: Adding the number '14' to item '3', so that it will become "3": [11, 12, 13, 14].
Is there a way to just add a single value to an array without rewriting the whole thing? It seems like I may have to get the value of the array associated with a key, add a new value to it, and then push the whole thing back, but I wanted to check if there's a simpler way to go about doing this. Thanks!
Upvotes: 0
Views: 500
Reputation: 598728
To add an item to an array, you need to know how many items there already are in that array.
To know how many items are in a Firebase collection, you need to download those items (or keep a separate counter, but I'm going to ignore that for now).
This is one of the many reasons why the Firebase documentation recommends against using an array to store collections of data.
The recommended solution is to use a so-called "push id", which are the very long cryptic looking values that are generated when your call ref.push()
in the Firebase JavaScript SDK.
{
"messages": {
"-JhLeOlGIEjaIOFHR0xd": "Hello there!",
"-JhQ76OEK_848CkIFhAq": "Push IDs are pretty magical.",
"-JhQ7APk0UtyRTFO9-TS": "Look a white rabbit!"
}
}
To learn more about what these push ids are, read this blog post explaining them.
Upvotes: 3