【问题标题】:Object to array - quick conversion对象到数组 - 快速转换
【发布时间】:2013-08-02 09:03:48
【问题描述】:

我有一个这样的 Json 结构:

这是从后端生成的(我使用的是 Firebase)并放入一个变量中:

var newJson = {}

我正在使用 AngularJS 和 ng-repeat 虽然这个变量来显示结果 - 它有效。我想通过投票属性订购 JSON,我尝试使用 angularJS

| orderBy: 'vote' "

但这不起作用,因为我是“ng-repeating”,虽然是 JSON 而不是数组。 我尝试了https://github.com/angular/angular.js/issues/1286 上显示的不同解决方案 但我无法让他们中的任何一个工作。

所以我想走简单的路并将我的 JSON 转换为数组。 我试过了:

 var arreyM = [];
 for (var i = 0; i < $scope.newJson.length; i++) {
      arreyM.push(name: $scope.newJson[i].name, pic: $scope.newJson[i].pic, vote:$scope.newJson[i].vote); 
 }

但它给了我错误-我猜语法是错误的。

【问题讨论】:

    标签: javascript angularjs firebase


    【解决方案1】:

    试试这个

    var arreyM = [];
     for (var i = 0; i < $scope.newJson.length; i++) {
          arreyM[i]['name']= $scope.newJson[i].name;
          arreyM[i]['pic']= $scope.newJson[i].pic
          arreyM[i]['pic'] =  $scope.newJson[i].vote; 
     }
    

    希望对你有帮助

    【讨论】:

    • 它是 consol log 这个:[] ......我不需要以某种方式将数据“推入”arrey 吗?
    • 您必须创建对象 arreyM[i] = {}; 并且 $scope.newJson.length 将未定义,因为 newJson 不是数组...
    • @AlexGarulli 试试看,我们正在放置像 arreyM[i]['name'] 这样的数据
    • 是的...有效...var arreyM = [] for (var i in newJson) { arreyM [i] = {} arreyM[i]['name']= newJson[i ]。姓名; arreyM[i]['pic']= newJson[i].pic arreyM[i]['vote'] = newJson[i].vote; }
    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多