Firebase强制使用map而不是array

时间:2016-02-25 10:24:46

标签: firebase angularfire

在firebase quide中我读到了关于数组: https://www.firebase.com/docs/web/guide/understanding-data.html#section-arrays-in-firebase

特别是:

  

但是,为了帮助在Firebase数据库中存储数组的开发人员,使用val()或REST api读取数据时,如果数据看起来像数组,Firebase客户端会将其呈现为数组。特别是,如果所有键都是整数,并且对象中超过一半的键与对象中的最大键具有非空值,则Firebase客户端会将其呈现为数组。后一部分很重要,请记住。

有没有办法强制firebase只使用map并且永远不会将数据转换为数组?任何配置?

在我的firebase示例中,我有这样的结构:

{ "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
    }
  }
} 
}

在java脚本中,我读取json之类的数组,因为firebase是智能的并且将我的数据转换为数组但是,我希望map。对我来说这种行为非常 不稳定。

 [ {
      "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 个答案:

答案 0 :(得分:3)

永远不会获得数组的最简单方法是始终使用字符串作为键。如果您的自然键是数字,请在前面添加一个字符串。

E.g。

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

这样你最终会得到:

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

Firebase永远不会将其强制转换为阵列。