Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single integer as key in firebase (Firebase array behavior)

Tags:

firebase

If I insert data into node/a/0 in firebase.

the result will treat a is an array a[0].

The same way, if I set my data in node/a/1 the first array will become null

      "a" : [ null, {
        "-J-22j_Mb59l0Ws0H9xc" : {
          "name" : "chok wee ching"
        }
      } ]

But it will be fine if node/a/2

      "a" : {
        "2" : {
          "-J-25xjEXUqcpsC-5LOE" : {
            "name" : "chok wee ching"
          }
        }
      }

my guess, firebase automatically treat single 0 and 1 as an array. How can I prevent this?

like image 350
vzhen Avatar asked Dec 21 '22 02:12

vzhen


1 Answers

Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.

However, to help people that are storing arrays in Firebase, when you call .val() or use the REST api to read data from Firebase, if the data looks like an array, Firebase will render it as an array.

In particular, if all of the keys are integers, and more than half of the keys between 0 and the maximum key in the object have non-empty values, then Firebase will render it as an array. It's this latter part of the heuristic that you are running into. Your second example only sets a value for 2, not 0 and 1, so less than half of the keys have values, and therefore Firebase renders it as an object.

You can't currently change or prevent this behavior (though it's a common source of confusion so we'll likely make some tweaks here in the future). However it's usually very easy to deal with the behavior once you understand it. If you need further help, perhaps you can expand your question to explain what you need to accomplish and how this behavior is preventing it.

like image 73
Michael Lehenbauer Avatar answered Jun 16 '23 14:06

Michael Lehenbauer