Lodash迭代嵌套循环

时间:2017-08-17 22:06:51

标签: javascript ecmascript-6 lodash

我正在尝试遍历下面的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;
};

1 个答案:

答案 0 :(得分:1)

function filterByTags(collections, filterTags) {
    return _.filter(collections, collection => {
        return _.some(collection.tags, collectionTag => {
            return _.includes(filterTags, collectionTag.name);
        });
    });
}