Can _lodash test an array to check if an array element has a field with a certain value?

六眼飞鱼酱① 提交于 2019-11-30 07:59:16
Felix Kling

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.

There is also a bit more elegant form:

var result = _.some(objectiveDetail.subTopics, {subTopicId: selectedSubTopicId});

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!