我有数组对象的结果,需要在带有 response_id
的过滤器中应用。该键存在于响应的子级中。如果我使用 23764、23765 进行搜索,我想要所有具有至少 2 个响应(ID 为 23764 和 23765)的问题对象,并且这是我想要在响应数组中唯一的两个响应对象。
如果我仅使用 23764 进行搜索,我想要所有具有该 id 的响应对象的 Question 对象,并且仅在数组中包含该响应对象。
我当前的实现尝试做这样的事情:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$filter) {
$scope.data = [
{
"id": "1341",
"question": "What about this chaneel?",
"response": [
{
"response_id": "23764",
"comment": "Every thing "
},
{
"response_id": "23765",
"comment": "No"
},
{
"response_id": "23766",
"comment": ".."
}
]
},
{
"id": "1342",
"question": "What dislike about this chaneel?",
"response": [
{
"response_id": "23764",
"comment": "Nothing"
},
{
"response_id": "23765",
"comment": "No"
},
{
"response_id": "23766",
"comment": ".."
}
]
},
{
"id": "1343",
"question": "What suggestion(s) this chaneel?",
"response": [
{
"response_id": "23764",
"comment": "Nothing "
},
{
"response_id": "23765",
"comment": "No"
},
{
"response_id": "23766",
"comment": ".."
}
]
}
];
var res = ($filter('filter')($scope.data, {response:{response_id:'23764,23765'}}, true));
console.log(res);
});
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
期望的结果
[
{
"id": "1341",
"question": "What about this chaneel?",
"response": [
{
"response_id": "23764",
"comment": "Every thing "
},
{
"response_id": "23765",
"comment": "No"
}
]
},
{
"id": "1342",
"question": "What dislike about this chaneel?",
"response": [
{
"response_id": "23764",
"comment": "Nothing"
},
{
"response_id": "23765",
"comment": "No"
}
]
},
{
"id": "1343",
"question": "What suggestion(s) this chaneel?",
"response": [
{
"response_id": "23764",
"comment": "Nothing "
},
{
"response_id": "23765",
"comment": "No"
}
]
}
]
最佳答案
因此,您使用 23764,23765
进行过滤,并且需要一组所有问题,其中包含一个 ID 为 23764
的响应对象 AND 一个响应ID 为 23765
的对象,这些应该是返回结果嵌套响应数组中的唯一响应对象。
有很多方法可以为此编写自定义过滤器函数。
这是一个例子:
var myFilter = function(collection, values) {
values = values.replace(' ', '').split(',');
var result = [];
collection.forEach(function(question) {
var questionMatches = [];
question.response.forEach(function(r) {
if (values.indexOf(r.response_id) > -1) questionMatches.push(r);
});
if (questionMatches.length !== values.length) return;
var questionCopy = angular.extend({}, question);
questionCopy.response = questionMatches;
result.push(questionCopy);
});
return result;
};
var filterValues = '23764, 23765';
var result = myFilter($scope.data, filterValues);
您可能想要添加一些参数检查,并且可能可以对其进行优化,但它至少应该让您开始。
可能还需要根据您是否需要原始数据或引用的副本来更改逻辑。
关于javascript - Angular JS 中的响应子节点应用于多维数组对象中的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613115/