如何转换' n'将对象转换为数组

时间:2017-11-27 07:07:05

标签: javascript angularjs

在对api响应和今天的日期进行比较后,我得到了一些对象:

function taffy() {
  var d = new Date();
  $scope.day = d.getDate();
  $scope.month = d.getMonth() + 1;
  $scope.year = d.getFullYear();
  $scope.today = $scope.year + "-" + $scope.month + "-" + $scope.day + "T00:00:00";
}

function getBackAll() {
  $http.get('api/Invoice?')
    .then(function(data) {
      $scope.amadeus = data.data.Response;

      for (var i = 0; i < $scope.amadeus.length; i++) {
        if ($scope.amadeus[i].ProgramPayDate === $scope.today && $scope.amadeus[i].StatusId === 3) {
          $scope.viroba = $scope.amadeus[i];
          //console.log($scope.viroba);
        }
      };
      //console.log($scope.amadeus);
    });
}

回复是&#39; n&#39;物体数量。我想要做的是在我的HTML视图上显示信息,但我不能。以前我问过,有人告诉我,我需要将对象转换为数组,但我在互联网上找到的对我来说并不是很有用。

让我说我的控制台上有下一个回复:

{id: 1, name: "Arthur", nickname: "mercury"}
{id: 2, name: "Chuck", nickname: "lemmy"}

如何获取信息并在html视图的表格中显示?

<table align="center">
    <thead>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Nickname</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <th>{{id}}</th>
        <th>{{name}}</th>
        <th>{{nickname}}</th>
    </tr>
    </tbody>
</table>

如果我只获得一个值,则表明没有问题。当我有一个以上时,就会出现问题。

有人可以帮助我吗?

提前完成。

1 个答案:

答案 0 :(得分:1)

您可以将对象列表存储在一个数组中,暂时假定它是usersusers看起来像这样

users = [{id: 1, name: "Arthur", nickname: "mercury"},
           {id: 2, name: "Chuck", nickname: "lemmy"}]

在您的代码中,尝试将amadeus[i]填充到users数组中,如下所示

function getBackAll() {
  $scope.users = []; // Or initialise this wherever logical
  $http.get('api/Invoice?')
    .then(function(data) {
      $scope.amadeus = data.data.Response;

      for (var i = 0; i < $scope.amadeus.length; i++) {
        if ($scope.amadeus[i].ProgramPayDate === $scope.today && $scope.amadeus[i].StatusId === 3) {
          $scope.users.push($scope.amadeus[i]);
          //console.log($scope.viroba);
        }
      };
      //console.log($scope.amadeus);
    });
}

您可以使用ngRepeat迭代您在控制器中填充的users数组。 https://docs.angularjs.org/api/ng/directive/ngRepeat

<table align="center">
    <thead>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Nickname</th>
    </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
            <th>{{user.id}}</th>
            <th>{{user.name}}</th>
            <th>{{user.nickname}}</th>
        </tr>    
    </tbody>
</table>