Angular Firebase从匿名用户检索收集的数据

时间:2015-01-28 03:13:54

标签: javascript json angularjs firebase

我有一个使用Angular和Firebase的调查系统,它将用户答案的​​结果存储在特定于每个用户的对象中。这适用于存储数据,但我已经意识到由于每个对象具有唯一的名称,可能很难将数据拉回。

我想循环遍历每个对象并将所有值拉到一起。因此,对于所有50个条目,找到comprehension.icons.damage [1]

的总和

如何构建一个遍历具有唯一名称的对象的循环,如下面的对象?

这是我的json结构

  "usersanonymous:-JgTyGt6An3WWyLvnnuu" : {
"comprehension" : {
  "-JgTzC0r_H58n7y8Al_-" : {
    "date" : 1422154060632,
    "icons" : [ {
      "damage" : [ null, "0", "3", "3" ],
      "ocular" : [ null, "2", "3", "1" ],
      "physical therapy" : [ null, "0", "4", "4" ],
      "skin" : [ null, "4", "0", "1" ]
    } ]
  }
}


 },
  "usersanonymous:-JgU-ryIpI-HR7D4VDkp" : {
    "comprehension" : {
      "-JgU0MwBwisNbjvRFGOT" : {
        "date" : 1422154629142,
        "icons" : [ {
          "damage" : [ null, "0", "3", "4" ],
          "ocular" : [ null, "1", "4", "3" ],
          "physical therapy" : [ null, "2", "4", "3" ],
          "skin" : [ null, "4", "1", "3" ]
        } ]
      }
    }
  }

1 个答案:

答案 0 :(得分:2)

根据你的输入数据,我会创建一个函数来提取你感兴趣的数据。我用原始的javascript编写了这个 - 如果你使用的是jQuery,你可以使用$ .map而不是(x in y)。


var data = {
    "usersanonymous:-JgTyGt6An3WWyLvnnuu": {
        "comprehension": {
            "-JgTzC0r_H58n7y8Al_-": {
                "date": 1422154060632,
                "icons": [{
                    "damage": [null, "0", "3", "3"],
                    "ocular": [null, "2", "3", "1"],
                    "physical therapy": [null, "0", "4", "4"],
                    "skin": [null, "4", "0", "1"]
                }]
            }
        }
    },
    "usersanonymous:-JgU-ryIpI-HR7D4VDkp": {
        "comprehension": {
            "-JgU0MwBwisNbjvRFGOT": {
                "date": 1422154629142,
                "icons": [{
                    "damage": [null, "0", "3", "4"],
                    "ocular": [null, "1", "4", "3"],
                    "physical therapy": [null, "2", "4", "3"],
                    "skin": [null, "4", "1", "3"]
                }]
            }
        }
    }
};

function extractComprehension(rawData) {
    var result = [];

    for (var usersanonymous in rawData) {
        usersanonymous = rawData[usersanonymous];
        if (usersanonymous.comprehension) {
            for (var token in usersanonymous.comprehension) {
                token = usersanonymous.comprehension[token];
                if (token.icons) {
                    result.push(token.icons[0]);
                }
            }
        }
    }

    return result;
}

function sumOf(objectList, property, index) {
    var result = 0;

    for (var o in objectList) {
        var numbers = (objectList[o][property] || []);

        if (numbers.length >= index) {
            result += parseInt(numbers[index], 10);
        }
    }

    return result;
}

使用此迷你api,您可以获得您感兴趣的属性总和:


// Get the data array.
var comprehension = extractComprehension(data);

// Sum some property.
console.log(sumOf(comprehension, 'damage', 3));