如何从浅层检索任意Firebase子级? [英] How do I retrieve arbitrary Firebase children from shallow level?

查看:45
本文介绍了如何从浅层检索任意Firebase子级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非规范化的数据,如下所示:

I have a denormalized data as follows:

- geohash
  - w22
    - qt4
      - vhy
        - e1c
          - IzjfhqsUhJU_XQSBGTv
            - authorid: 
            - authorname: 
            - content: 

           -Izjv10JcaS7fae6dmqb
            - authorid: 
            - authorname: 
            - content: 
      - vhz
        - erc
          -Izjv10JcaS7fae6dmqb
            - authorid: 
            - authorname: 
            - content: 
  - z99
    - qt4
      - abd
        - 4g5
          -Izjv10JcaS7fae6dmqb
            - authorid: 
            - authorname: 
            - content: 

我想在 geohash/w22/qt4 下列出 authorid,作者名,内容的所有值.但是我不提前知道孩子的名字是什么,或者确切地知道层次结构中那个级别上有多少孩子.

I want to list all values for authorid, authorname, content under geohash/w22/qt4. But I don't know ahead of time what the children names are or exactly how many are at that level in the hierarchy.

在这个较浅的级别上,该代码应如何枚举子级子代?

What should the code look like to enumerate the subchildren at this shallow level?

    var fooRef = new Firebase('firebaseRef/geohash/w22/qt4');
    fooRef.on('child_added', function(snapshot) {  
      //Need help here.
    });

推荐答案

当您需要浅谈一些孩子,而又不知道密钥名称时,可以使用 DataSnapshot.forEach()进行枚举.另外,您可以通过 DataSnapshot.val()获得父级的JS对象,并使用常规的JS对象/键枚举对原始对象进行枚举.另请参见:如何列出javascript对象的属性.

When you need to get a hold of children at a shallow level and you don't know the key names before hand you can use DataSnapshot.forEach() for enumeration. Alternatively, you can get the JS object at the parent level via DataSnapshot.val() and enumerate against the raw object using normal JS object/key enumeration; see also: How to list the properties of a javascript object.

因此,为了填写您的示例,它看起来像这样:

So, to fill out your example, it would look like this:

var fooRef = new Firebase('firebaseRef/geohash/w22/qt4');
fooRef.on('child_added', function f(snapshot) { 
  snapshot.forEach(function(level1) {
     level1.forEach(function(level2) {
        var entry = level2.val(); // contains the JS object with authorid, authorname, ...
        var pathToEntry = snapshot.name() + "/" + level1.name() + "/" + level2.name(); // contains the path with the unknown children names
     });
  });
});

我创建了一个带有示例Firebase的JSFiddle,其中包含了如所述填充的数据以及将子项输入拉出的代码.请在这里看看: http://jsfiddle.net/guy5n/1/

I have created a JSFiddle with an example Firebase with data populated as described, as well as code that pulls the subchildren entries out. Please take a look here: http://jsfiddle.net/guy5n/1/

这篇关于如何从浅层检索任意Firebase子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆