我如何将我从Firebase检索的新Object数据转换为JSON表单,就像我之前一样

时间:2014-07-30 17:15:27

标签: javascript json angularjs firebase angularfire

我刚用我的Yeoman,AngularJS应用程序设置了我的Firebase,angularFire数据库。我之前用来硬编码我的数据

$scope.data = [
    { name: 'NAME', description: 'DESCRIPTION', type: 'TYPE', etc: 'ETC', etc: 'ETC', etc: 'ETC'... },
    { name: 'NAME', description: 'DESCRIPTION', type: 'TYPE', etc: 'ETC', etc: 'ETC', etc: 'ETC'... },
    { name: 'NAME', description: 'DESCRIPTION', type: 'TYPE', etc: 'ETC', etc: 'ETC', etc: 'ETC'... },
    ...
    ...
    More Data...
    ...
    ...
    { name: 'NAME', description: 'DESCRIPTION', type: 'TYPE', etc: 'ETC', etc: 'ETC', etc: 'ETC'... }
]

当我将上述数据上传到我的Firebase数据库时,我必须有一个有效形式的JSON数据,所以我将其转换为此

[
    { "name": "NAME", "description": "DESCRIPTION", "type": "TYPE", "ect": "ETC","ect": "ETC","ect": "ETC"... },
    { "name": "NAME", "description": "DESCRIPTION", "type": "TYPE", "ect": "ETC","ect": "ETC","ect": "ETC"... },
    { "name": "NAME", "description": "DESCRIPTION", "type": "TYPE", "ect": "ETC","ect": "ETC","ect": "ETC"... },
    ...
    ...
]

是有效的JSON格式。现在,当我在console.log(firebaseRef)中时,我的数据将在下面的表单中被检索到。这正是我在Google Chrome控制台中看到的内容。

Object {$bind: function, $add: function, $save: function, $set: function, $transaction: function…}
    0: Object
         description: "DESCRIPTION""
         name: "NAME"
         type: "TYPE""
         etc: "ETC"
         etc: "ETC"
         etc: "ETC"
         ...more data...
         __proto__: Object
    1: Object
         description: "DESCRIPTION""
         name: "NAME"
         type: "TYPE""
         etc: "ETC"
         etc: "ETC"
         etc: "ETC"
         ...more data...
         __proto__: Object
    2: Object
         description: "DESCRIPTION""
         name: "NAME"
         type: "TYPE""
         etc: "ETC"
         etc: "ETC"
         etc: "ETC"
         ...more data...
         __proto__: Object
    ...
    ...
    ...More Data...
    ...
    ...

如何将我从Firebase检索的新对象数据转换为与之前相同的格式?

这是两者之间主要区别的图片。我收到的Firebase数据似乎是一个包含多个对象的对象,我之前想要/使用的数据是多个对象的数组。 picture of two different Object data

1 个答案:

答案 0 :(得分:1)

根据此网址:Object to array - quick conversion

您需要将firebase对象分配给变量:

$scope.firebaseObj

然后您可以通过以下方式将其填充到$ scope.data对象中:

$scope.data = [];
 for (var i = 0; i < $scope.firebaseObj.length; i++) {
      $scope.data[i]['name']= $scope.firebaseObj[i].name;
      $scope.data[i]['description']= $scope.firebaseObj[i].description;
      $scope.data[i]['type'] =  $scope.firebaseObj[i].type;
      $scope.data[i]['etc1'] =  $scope.firebaseObj[i].etc1;
      $scope.data[i]['etc12'] =  $scope.firebaseObj[i].etc2;
      .
      .
      . 
 }

仅当JSON中的每个元素具有相同的属性时才会起作用