如何在AngularJS中的数组内添加数组中的值

时间:2016-08-01 06:05:44

标签: angularjs multidimensional-array

如果我的标题听起来如此令人困惑,我道歉,因为我不知道如何准确地说出来。基本上,这就是我想要做的。

例如,我有以下数组:

var sourceArray = [
     { question: "Question 1", inputType: "radio", answer: "Answer 1", id: "1" },
     { question: "Question 1", inputType: "radio", answer: "Answer 2", id: "2" },
     { question: "Question 1", inputType: "radio", answer: "Answer 3", id: "3" },
     { question: "Question 2", inputType: "radio", answer: "Answer 1", id: "4" },
     { question: "Question 2", inputType: "radio", answer: "Answer 2", id: "5" },
     { question: "Question 2", inputType: "radio", answer: "Answer 3", id: "6" }
]

我想对其进行重组,以便它看起来像这样:

var newArray = [
     {
      question: "Question 1", inputType: "radio", 
      choices: [{answer: "Answer 1", id: "1"},
                {answer: "Answer 2", id: "2"},
                {answer: "Answer 3", id: "3"}
               ]},
     {
      question: "Question 2", inputType: "radio", 
      choices: [{answer: "Answer 1", id: "4"},
                {answer: "Answer 2", id: "5"},
                {answer: "Answer 3", id: "6"}
     ]}
]

答案按问题分组,因此如果sourceArray中的下一个问题与当前问题相同,则会将答案推送到choices数组。

AngularJS中是否可以使用angular.forEach?

任何帮助将不胜感激。

感谢您的回复。

3 个答案:

答案 0 :(得分:2)

你走了。请参阅下面的工作示例:



// Add a hepler method in the Array to find the value
Array.prototype.find = function(key, value) {
  var index = -1;
  angular.forEach(this, function(item, i) {
    if (item[key] === value) {
      index = i;
    }
  });

  return this[index];
};

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {

  $scope.sourceArray = [{
    question: "Question 1",
    inputType: "radio",
    answer: "Answer 1",
    id: "1"
  }, {
    question: "Question 1",
    inputType: "radio",
    answer: "Answer 2",
    id: "2"
  }, {
    question: "Question 1",
    inputType: "radio",
    answer: "Answer 3",
    id: "3"
  }, {
    question: "Question 2",
    inputType: "radio",
    answer: "Answer 1",
    id: "4"
  }, {
    question: "Question 2",
    inputType: "radio",
    answer: "Answer 2",
    id: "5"
  }, {
    question: "Question 2",
    inputType: "radio",
    answer: "Answer 3",
    id: "6"
  }];

  $scope.newArray = [];

  $scope.convert = function() {
    // Iterate array
    angular.forEach($scope.sourceArray, function(item) {
      // Check if the question alrady exists
      if (!$scope.newArray.find('question', item.question)) {
        // If not, push the question to the array with empty choices
        $scope.newArray.push({
          question: item.question,
          inputType: item.inputType,
          choices: []
        });
      }

      var newArrayItem = $scope.newArray.find('question', item.question);
      
      // Push the choices
      newArrayItem.choices.push({
        answer: item.answer,
        id: item.id
      });
    });
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">


<div ng-app="sa" ng-controller="FooController">
  Before:
  <br>{{sourceArray | json}}
  <br>
  <a href="" ng-click="convert()">convert</a>
  <br>After:
  <br>{{newArray | json}}
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用for循环将

组合在一起

以下是代码:

function transformArr(orig) {
    var newArr = [],
        answers = {},
        newItem, i, j, cur;
    for (i = 0, j = orig.length; i < j; i++) {
        cur = orig[i];
        if (!(cur.question in answers)) {
            answers[cur.question] = {question: cur.question, answers: [],inputType : cur.inputType,id :cur.id};
            newArr.push(answers[cur.question]);
        }
        answers[cur.question].answers.push(cur.answer);
    }
    return newArr;
}

工作App

答案 2 :(得分:0)

您需要filter中的sourceArray,两个问题列表,如下所示:

var question1 = $filter('filter')(sourceArray, {
  question: 'Question 1'
});
var question2 = $filter('filter')(sourceArray, {
  question: 'Question 2'
});

之后,您应该创建一个新的数组数据,如下所示:

$scope.questionData = [{
  "question": "Question 1",
  "inputType": "radio",
  "choices": []
}, {
  "question": "Question 2",
  "inputType": "radio",
  "choices": []
}];

然后,你应该在两个过滤的变量上运行循环到新的对象数组中:

1):

angular.forEach(question1, function(value, key) {
  if (value.question == $scope.questionData[0].question) {
    $scope.questionData[0].choices.push({
      'answer': value.answer,
      'id': value.id
    });
  }
});

2):

angular.forEach(question2, function(value, key) {
  if (value.question == $scope.questionData[1].question) {
    $scope.questionData[1].choices.push({
      'answer': value.answer,
      'id': value.id
    });
  }
});

请参阅此处demo