gpt4 book ai didi

javascript - 我如何将从 Firebase 检索的新对象数据转换为 JSON 形式,就像以前一样

转载 作者:行者123 更新时间:2023-11-28 01:06:19 25 4
gpt4 key购买 nike

我刚刚使用 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

最佳答案

根据这个网址: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 中的每个元素都具有相同的属性时,这才有效

关于javascript - 我如何将从 Firebase 检索的新对象数据转换为 JSON 形式,就像以前一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com