【发布时间】:2017-08-17 22:06:51
【问题描述】:
我正在尝试遍历下面的 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;
};
【问题讨论】:
-
您错误地使用了
_.map。在你认为你回来之后它仍然在循环
标签: javascript ecmascript-6 lodash