Firebase force to use map rather than array

蓝咒 提交于 2021-02-10 23:31:16

问题


In firebase quide i read about array: https://www.firebase.com/docs/web/guide/understanding-data.html#section-arrays-in-firebase

especially :

However, to help developers that are storing arrays in a Firebase database, when data is read using val() or via the REST api, if the data looks like an array, Firebase clients 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 clients will render it as an array. This latter part is important to keep in mind.

Is there any way to force firebase to use only map and never convert data to array? Any configuration?

In my example in firebase i have got structure like that:

{ "0": {
  "drivers" : {
    "12" : {
      "latitude" : 50.076574,
      "longitude" : 19.9209708,
      "timestamp" : 1456311442329
    },
    "13" : {
      "latitude" : 50.0166148,
      "longitude" : 20.9863258,
      "timestamp" : 1456395866163
    }
  }
}
},
{ "1" : {
  "drivers" : {
    "10" : {
      "driver_id" : 10,
      "latitude" : 50.076574,
      "longitude" : 19.9209708,
      "timestamp" : 1456311442329
    },
    "17" : {
      "driver_id" : 17,
      "latitude" : 50.0166148,
      "longitude" : 20.9863258,
      "timestamp" : 1456395866163
    }
  }
} 
}

And in java script i read json like array, because firebase is smart and convert my data to array but, i expect map. This behavior for me is very unstable.

 [ {
      "drivers" : {
        "12" : {
          "latitude" : 50.076574,
          "longitude" : 19.9209708,
          "timestamp" : 1456311442329
        },
        "13" : {
          "latitude" : 50.0166148,
          "longitude" : 20.9863258,
          "timestamp" : 1456395866163
        }
      }
    }, {
      "drivers" : {
        "10" : {
          "driver_id" : 10,
          "latitude" : 50.076574,
          "longitude" : 19.9209708,
          "timestamp" : 1456311442329
        },
        "17" : {
          "driver_id" : 17,
          "latitude" : 50.0166148,
          "longitude" : 20.9863258,
          "timestamp" : 1456395866163
        }
      }
    } ]

回答1:


The easiest way to never get an array is to always use strings as keys. If your natural keys are numbers, prefix them with a string.

E.g.

var words = ['zero', 'one', 'two', 'three'];
words.forEach(function(word, index) {
  ref.child('word_'+index).set(word);
});

This way you'll end up with:

{
  "word_0": "zero",
  "word_1": "one",
  "word_2": "two",
  "word_3": "three"
}

And Firebase will never coerce it into an array.



来源:https://stackoverflow.com/questions/35624566/firebase-force-to-use-map-rather-than-array

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