【问题标题】:reverse objects of objects angularjs对象angularjs的反向对象
【发布时间】:2017-07-03 10:41:04
【问题描述】:

目前我遇到了一个问题,我有一些问题和数据键 我想显示数据的方式是首先我的密钥应该出现然后我的数据问题出在我的数据中

    {
  "0": [
    {
      "question": "How often is real property re-assessed (or revalued)?",
      "id": 1,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often second?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often third?",
      "id": 2,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "key": "Survey Meta Data"
    }
  ],
  "1": [
    {
      "question": "When are New Assessment Notices sent out?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 1
    },
    {
      "key": "Assessment"
    }
  ]
}

当我对这些数据使用 ng-repeat 时,我得到了这样的结果:

<div ng-repeat="data in viewQuestions">
<div class="panel panel-default"  ng-repeat="value in data">
     {{value.key}}

   label>{{value.question}} </label>

     </div>
      </div>

先显示我的问题,然后显示密钥,但我想先显示密钥,然后显示问题 我知道问题首先显示问题,因为它们是先插入的,然后是数据键。

有什么方法可以让我反转数据,以便首先显示 key,然后显示我的 questions

【问题讨论】:

    标签: angularjs angularjs-ng-repeat arrayobject


    【解决方案1】:

    您需要的是数据按摩,以将数据结构更改为您需要的格式。

    var processedData = [];
    angular.forEach(data, function(item) {
      var section = { questions: [] };
    
      angular.forEach(data, function(question) {
        if (question.key) { // this is key, not question
          section.key = question.key;
        }
        else {
          section.questions.push(question);
        }
      });
    
      processedData.push(section);
    });
    

    【讨论】:

    • question .key 不是它的 data.question
    • @KumailHussain 您的数据中有数组数组,您可能需要合并它们?
    • 你说的结合是什么意思??
    【解决方案2】:

    在挖掘之后,我想出了一个完美的解决方案: 首先使用此过滤器反转数组:

     .filter("reverse", function(){
        return function(items){
            return items.slice().reverse(); // Create a copy of the array and reverse the order of the items
        };
    });
    

    在 html 中添加这一行

    <div class="panel panel-default"  ng-repeat="value in data |reverse">
    

    先显示now键,然后显示问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-24
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 2016-12-27
      相关资源
      最近更新 更多