问题
I have a variable selectedSubTopicId and I have an array of subTopic objects: objectiveDetail.subTopics[]. Each subTopic object has a field subTopicId
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.
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}]
}
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.
回答1:
You didn't ask for how to do it, but I assume that's what you wanted to know.
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 will skip the remaining elements if it found one for which the callback returned true.
回答2:
There is also a bit more elegant form:
var result = _.some(objectiveDetail.subTopics, {subTopicId: selectedSubTopicId});
回答3:
You can use _.some method, like this
var _ = require("lodash");
var objectiveDetail = {"objectiveDetailId":285,
"objectiveId":29,
"number":1,
"text":"x",
"subTopics":[{"subTopicId":1,
"number":1}]
};
var selectedSubTopicId = 1;
if (_.some(objectiveDetail.subTopics, function(currentTopic) {
return currentTopic.subTopicId === selectedSubTopicId;
})) {
console.log("selectedSubTopicId exists");
}
Output
selectedSubTopicId exists
回答4:
This one worked for me very well: It helps where you have many columns of data to check against, say title, category and description.
To check if stringTosearch is found in any of those columns of data, you can do:
let searchResults = _.filter(yourArrayHere, (item) => {
return item.title.indexOf(stringTosearch) > -1
|| item.category.indexOf(stringTosearch) > -1
|| item.description.indexOf(stringTosearch) > -1;
});
It will return any object of your array that has stringTosearch in any of the columns you specified.
来源:https://stackoverflow.com/questions/21278661/can-lodash-test-an-array-to-check-if-an-array-element-has-a-field-with-a-certai