我正在尝试遍历下面的Collections JSON对象。我试图找到具有tagArray标签之一的集合元素。基本上这是一个过滤器练习,其集合元素具有从tagArray中选择的标记。
{
1: {
"description": "AAA",
"tags": [
{
"name": "tag1",
},
{
"name": "tag2",
},
{
"name": "tag3",
},
],
"name": "XYZ",
},
2: {
"description": "BBB",
"tags": [
{
"name": "tag1",
}
],
"name": "CCC",
},
3: {
"description": "xms",
"tags": [],
"name": "Huo",
},
4: {
"description": "asd",
"tags": [],
"name": "TXS",
}
}
tagArray如下所示:[tag1,tag2,...]
我使用lodash将其编码如下,它工作正常。但我不确定我是否可以进一步提高这一点以及如何改进?
const filterByTags = (collections, filterTags) => {
let filteredCollections = _.pickBy(collections, (collection) => {
let collectionWithTag = false;
_.map(collection.tags, (collectionTag) => {
if (filterTags.indexOf(collectionTag.name) !== -1) {
collectionWithTag = true;
return collectionWithTag;
}
});
return collectionWithTag;
});
return filteredCollections;
};
答案 0 :(得分:1)
pickBy
,而是filter
(Lodash / native)map
,而是some
(Lodash / native)indexOf
,而是includes
(Lodash / native)
function filterByTags(collections, filterTags) {
return _.filter(collections, collection => {
return _.some(collection.tags, collectionTag => {
return _.includes(filterTags, collectionTag.name);
});
});
}