可以_lodash测试一个数组来检查数组元素是否有一个具有特定值的字段? [英] Can _lodash test an array to check if an array element has a field with a certain value?
问题描述
我有一个变量 selectedSubTopicId
,我有一个subTopic对象数组: objectiveDetail.subTopics []
。每个 subTopic
对象都有字段 subTopicId
I have a variable selectedSubTopicId
and I have an array of subTopic objects: objectiveDetail.subTopics[]
. Each subTopic
object has a field subTopicId
我想用它来启用或禁用和添加主题按钮。我是否可以在ng-disabled中使用lodash来测试此数组,并且如果数组的任何 subTopic
对象元素具有 subTopicId $ c,则报告为true $ c>等于
selectedSubTopicId
。
I would like to use this to enable or disable and Add topic button. Can I use lodash in the ng-disabled to test this array and report true if any subTopic
object element of the array has a subTopicId
that is equal to the selectedSubTopicId
.
这是objectiveDetail中的数据样本。在这种情况下,subTopics数组中只有一个元素。
Here's a sample of the data that's in objectiveDetail. In this case there's just one element in the subTopics array.
{"objectiveDetailId":285,
"objectiveId":29,
"number":1,
"text":"x",
"subTopics":[{"subTopicId":1,
"number":1}]
}
这是我的角色控制器中由thefourtheye建议的代码:
Here is the code in my Angular Controller suggested by thefourtheye:
$scope.checkDuplicateSubTopicId = function (objectiveDetail, sSubTopic) {
if (_.some(objectiveDetail.subTopics, function(currentTopic) {
return _.contains(currentTopic, selectedSubTopicId);
})) {
return true;
} else {
return false;
}
}
点击功能未显示的我的按钮看起来像这样:
My button with the click function not shown looks like this:
<button data-ng-disabled="checkDuplicateSubTopicId(objectiveDetail, subTopicId)">
Add Topic
</button>
问题是它不能正常工作且按钮没有显示已禁用。
The problem is that it's not quite working and the button does not show disabled.
推荐答案
你没有要求怎么做,但我认为那是你想知道的。
正如我已经提到的,你可以使用 _。some
,它将迭代数组中的每个元素并执行回调。在该回调中,您可以测试主题属性的值是否等于变量的值:
As I already mentioned, you can use _.some
, which will iterate over every element in the array and execute a callback. In that callback you can test whether the value of the topic's property equals the value of the variable:
var result = _.some(objectiveDetail.subTopics, function (topic) {
return topic.subTopicId === selectedSubTopicId;
});
_。some
将跳过剩余的元素如果它找到了一个回调返回的 true
。
_.some
will skip the remaining elements if it found one for which the callback returned true
.
这篇关于可以_lodash测试一个数组来检查数组元素是否有一个具有特定值的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!