Angularjs按数组

时间:2016-06-21 11:00:20

标签: arrays angularjs json filter

我有一个带有多选选项的下拉列表。我想从基于该数组的复杂JSON中过滤掉数据。

选定的选项形成一组数据,如:

$scope.myval=["Adyar","Paris","central"];

我的JSON:

$scope.myTest={     
    "buslist":
        {
        "code":"1",
        "message":"Success",
        "fromStationCode":"71",
        "searchResult":[        {
        "arrivalTime":"17:00:00",
        "availableSeats":"42",
        "boardingPointDetails":[{
        "code":"1631",
        "name":"Koyambedu",
        "time":"09:30:00"
        },
        {
        "code":"961296",
        "name":"Paris",
        "time":"09:45:00"
        }
        ]
        ]
        },

         {
        "arrivalTime":"18:00:00",
        "availableSeats":"32",
        "boardingPointDetails":[{
        "code":"2084",
        "name":"Adyar",
        "time":"09:30:00"
        },
        {
        "code":"961296",
        "name":"Madurai",
        "time":"09:45:00"
        }
        ]
        ]
        }
        }
        ...
    };

我的HTML模板是:

                <tbody ng-repeat=" i in myTest.buslist.searchResult" >
                <tr>
                    <td>{{i.arrivalTime}}</td>
                    <td>{{i.availableSeats}}</td>

                    <td>
                    <p ng-repeat="m in i.boardingPointDetails">{{m.name}}</p>
                    </td>
                </tr>
            </tbody>

我想根据选定的值过滤我的数据。我尝试过这样的事情:

$scope.matched = $scope.myTest.buslist.searchResult.boardingPointDetails.name.indexOf(data);

即:所选选项必须与“boardingPointDetails”中的“name”字段匹配,但它失败。提前谢谢。

1 个答案:

答案 0 :(得分:0)

由于$scope.myTest.buslist.searchResult.boardingPointDetails是一个数组 $scope.myTest.buslist.searchResult.boardingPointDetails.name无效。

您需要使用Array函数来获得正确的结果:

$scope.matched = $scope.myTest.buslist.searchResult.boardingPointDetails.filter(function(el) {
   return el.name === data;
}).length > 0;

编辑:

由于您的评论,我们了解您希望获得与boardPointDetails选项之一具有相同name属性的data。其中data是一个字符串数组。

这将完成这项工作:

$scope.matched = $scope.myTest.buslist.searchResult.boardingPointDetails.filter(function(el) {
   return data.indexOf(el.name) === 1;
});