【问题标题】:Lodash iterate nested loopsLodash 迭代嵌套循环
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 如果我想返回一个对象而不是数组怎么办。 filter 方法将返回一个数组。在这种情况下使用pickBy是否明智?
  • @GauravShah 然后pickBy 可能会这样做,但最好使用数组。不要使用具有整数属性名称的对象。
  • 团队正在使用对象而不是数组,因此我们可以通过 id 对列表进行键控。 id 不一定是整数。在这里使用对象而不是数组是否合理?
  • 是的。这不是你原来的问题:-)
  • 我试图在这里使用虚拟数据。感谢您的投入:-)
猜你喜欢
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多