简体   繁体   English

迭代 JSON 文件并且没有在 Javascript 中正确返回结果

[英]Iterating JSON file and not returning result correctly in Javascript

I have a JSON file and iterating it.我有一个 JSON 文件并对其进行迭代。 If there is a column called "validation" : {"required"} then I add a count in a variable like below:如果有一列名为 "validation" : {"required"} 然后我在一个变量中添加一个计数,如下所示:

for (var a= 0; a<66; ++a) {
        var requiredFieldsInPart = 0;

            for (var b=0; b<$scope.groups[a].sections[0].fields.length; ++b) {
             try {
                 throw console.log($scope.groups[a].sections[0].fields[b]["validations"]["required"]);
             }
             catch (e) {
                 console.log(e);
             }
             requiredFieldsInPart += 1;
         }

The reason I'm using try/catch is because I wanna pass if there is an error.我使用 try/catch 的原因是因为我想在出现错误时通过。 There are some objects which do not have "validations" attribute so it was causing an error.有一些对象没有“验证”属性,因此导致错误。

Let's say there are total 21 fields in a section and 19 of them have "validations" and 2 do not have "validations" .假设一个部分共有 21 个字段,其中 19 个具有"validations" ,2 个没有"validations" So requiredFieldsInPart should return 19. However, it returns 21 right now.所以requiredFieldsInPart应该返回 19。但是,它现在返回 21。 How do I make sure it only counts an object with "validations" ??我如何确保它只计算具有"validations"的对象?

I would proceed by filtering the source array and returning the size of the result :我将继续过滤源数组并返回结果的大小:

return $scope.groups.filter(group =>
                             group.sections[0].fields[b].validations && 
                             group.sections[0].fields[b].validations.required
                           ).length
for (var a= 0; a<66; ++a) {
    var requiredFieldsInPart = 0;

        for (var b=0; b<$scope.groups[a].sections[0].fields.length; ++b) {
         try {
             console.log($scope.groups[a].sections[0].fields[b]["validations"]["required"]);
             requiredFieldsInPart += 1;//put this line inside 'try' block will do
         } catch (e) {
             console.log(e);
         }             
         }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM