如何获取嵌套在对象中的数组之和?

时间:2015-09-04 16:23:40

标签: javascript json angularjs

{service: {  
  categories: [
      {
          name: "category1",
          id: 1,
          questions: [
              {
                  id: 1,
                  question: "example trivia question here",
                  value: 2
              }, {
                  id: 2,
                  question: "example trivia question here",
                  value: 3
              }]
      },
    {
        name: "category2",
        id: 2,
        questions: [
            {
                id: 3,
                question: "example trivia question here",
                value: 5
            }
        ]
    },
    {
        name: "category3",
        id: 3
    }
]
}};

对于每个类别,我都在尝试计算回答的琐事问题。如何获得每个类别的已回答问题的总和(当存在值时指示)?我认为循环中出现了问题。我也尝试过使用数组原型。抱歉没有问题。

$scope.questionCount = 0;

angular.forEach($scope.service, function(categories, questions) {
  for (var i = 0; i < questions.length; i++) {
    if (questions[i].value !== null){
      triviaCount = 0
      triviaCount += 1
      $scope.questionCount.push(triviaCount)
    }
}
});

3 个答案:

答案 0 :(得分:0)

这样的事情? (看一下控制台)

控制台输出:

category1  # of quesitons:  2
category2  # of quesitons:  1
category3  # of quesitons:  0

&#13;
&#13;
var service = {  
    categories: [
        {
            name: "category1",
            id: 1,
            questions: [
                {
                    id: 1,
                    question: "example trivia question here",
                    value: 2
                }, {
                    id: 2,
                    question: "example trivia question here",
                    value: 3
                },
                {
                    id: 9,
                    question: "example trivia question here",
                    value: '',
                }
            ]
        },
        {
            name: "category2",
            id: 2,
            questions: [
                {
                    id: 3,
                    question: "example trivia question here",
                    value: 5
                },
                {
                    id: 7,
                    question: "example trivia question here",
                    value: '',
                }
            ]
        },
        {
            name: "category3",
            id: 3,
            questions: [],
        }
    ]
};
$(document).ready(function() {
	for(var i = 0; i < service.categories.length; i++ ){
        var questionCount = 0;
    	for(var j = 0; j < service.categories[i].questions.length; j++ ) {
        	if (service.categories[i].questions[j].value != '' && service.categories[i].questions[j].value != undefined) {
            	questionCount++;
            }            
        }
        console.log(service.categories[i].name, ' # of quesitons: ', questionCount);
    } 
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我不习惯角度js,但这就是我将如何处理js。我希望这会对你有所帮助。



    var json = {
        service: {
            categories: [{
                name: "category1",
                id: 1,
                questions: [{
                    id: 1,
                    question: "example trivia question here",
                    value: 2
                }, {
                    id: 2,
                    question: "example trivia question here",
                    value: 3
                }]
            }, {
                name: "category2",
                id: 2,
                questions: [{
                    id: 3,
                    question: "example trivia question here",
                    value: 5
                }]
            }, {
                name: "category3",
                id: 3
            }]
        }
    };

    var qCount = 0;

    categories = json.service.categories;
    for (var category in categories) {
        var temp = categories[category];
        if (temp.questions !== undefined) {
            var questions = temp.questions;
            for (var que in questions) {
                if (questions[que].value !== undefined)
                    qCount++;
            }
        }
    }

    console.log(qCount); //here is your question count


答案 2 :(得分:0)

使用Array提供的map()方法

var ajax = new function(){

    var self = this;

    self.x = function() {
        if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
            return new XMLHttpRequest();
        }else{// code for IE6, IE5
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    };

    self.send = function(url, callback, method, data, sync) {
        var x = self.x();
        x.open(method, url, sync);
        x.onreadystatechange = function() {
            if (x.readyState == 4) {
                callback(x.responseText)
            }
        };
        if (method == 'POST') {
            x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        }
        x.send(data)
    };

    self.get = function(url, data, callback, sync) {
        var query = [];
        for (var key in data) {
            query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
        self.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, sync)
    };


    self.post = function(url, data, callback, sync) {
        var query = [];
        for (var key in data) {
            query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
        self.send(url, callback, 'POST', query.join('&'), sync)
    };
};