简体   繁体   English

Lodash / JS-将_.find语句转换为_.forEach

[英]Lodash/JS - Convert _.find statement to _.forEach

I'm having trouble converting the following Lodash statement to something that works in an application that I inherited at work and am trying to fix bugs in. At the moment, we are having issues with only one device on our system returning when two devices have the same name and the following code seems to be the culprit as it would only return the first "true" value in an array: 我无法将下面的Lodash语句转换为在我在工作中继承的应用程序中正常工作的东西,并试图修复其中的错误。目前,我们遇到的问题是只有两个设备同时使用时,系统上的一个设备返回相同的名字和下面的代码似乎是罪魁祸首,因为它只会返回数组中的第一个“ true”值:

var group = _.find(groupList, {id: id});

How would I successfully convert this to a statement that iterates over all objects in an array and then returns those objects? 如何将其成功转换为对数组中所有对象进行迭代然后返回这些对象的语句? I've tried the following options to no avail: 我尝试了以下选项无济于事:

 var group = _.filter(groupList, {id: id});

and

 var group = _.every(groupList, {id: id});

and

 var group = _.forEach(groupList, {id: id}) 
 return {id};

I know I am probably missing something in my syntax. 我知道我的语法中可能缺少一些内容。 Any help would be much appreciated. 任何帮助将非常感激。 Running Lodash v3.7.0 运行Lodash v3.7.0

Here's the rest of the code in the directive in case anyone is interested or sees something else I might be missing: 这是指令中的其余代码,以防有人感兴趣或发现我可能会遗漏的其他内容:

define(['./../_module'], function (directives) {
'use strict';
directives.directive('dmGroupedList', ['$compile', '$state', 'APP_CONSTANTS', function ($compile, $state, APP_CONSTANTS) {
    return {
        restrict: 'A',
        scope: {
            items: '=',
            groupBy: '=',
            actions: '=',
            nonameGroupLabel: '='
        },
        templateUrl: function (elem, attrs) {
            return attrs.templateUrl || 'views/shared-templates/grouped-list.html';
        },
        link: function (scope, element, attrs) {
            scope.$watchGroup(['items', 'groupBy', 'nonameGroupLabel'], function () {
                scope.groupList = [];
                scope.groupedItems = {};

                var actions = scope.actions[scope.groupBy];

                _.forEach(scope.items, function (item) {
                    scope.handlers.getGroups(scope.groupList, item, scope.items, scope.groupBy, actions);
                });

                _.forEach(scope.groupList, function (group) {
                    var items = scope.groupedItems[group.id];
                    items = _.sortBy(items, function (item) {
                        return item.description;
                    });

                    scope.groupedItems[group.id] = items;
                });

                var groupsToSort = _.where(scope.groupList, {unassigned: false});
                var unassignedGroups = _.sortBy(_.where(scope.groupList, {unassigned: true}), 'name');
                scope.groupList = _.sortBy(groupsToSort, function (group) {
                    return group.name;
                });
                //adds unassigned groups to a new array via the javascript "push" method
                if (angular.isDefined(unassignedGroups)) {
                    for (var i = 0; i < unassignedGroups.length; i++) {
                        scope.groupList.push(unassignedGroups[i]);
                    }
                }
            });

            scope.handlers = {
                getGroups: function (groupList, item, items, groupBy, actions) {
                    var group = item[groupBy];

                    if (_.isEmpty(group)) {
                        scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                    }
                    else {
                        if (angular.isArray(group) || angular.isObject(group)) {
                            _.forEach(group, function (groupName) {
                                if (groupName == APP_CONSTANTS.ZERO) {
                                    scope.handlers.addGroupToList(groupList, APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE, items, groupBy, item, actions, scope);
                                    return;
                                }

                                scope.handlers.addGroupToList(groupList, groupName, items, groupBy, item, actions, scope);
                            })
                        } else {
                            scope.handlers.addGroupToList(groupList, group, items, groupBy, item, actions, scope);
                        }
                    }
                },
                addGroupToList: function (groupList, groupId, items, groupBy, item, handlers, scope) {
                    var id = _.camelCase(groupId);

                   var group = _.find(groupList, {id: id});
                    //var group = _.forEach(groupList, {id: id})
                    //return {id};

                    if (!group) {
                        var name = '';
                        var unassigned = false;
                        var link = null;

                        if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE || groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                            if (groupId == APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE_PARENT_ID) {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.NONE;
                            } else {
                                name = APP_CONSTANTS.DEVICE_NONE_NAME_MAPPING.UNASSIGNED;
                            }

                            unassigned = true;
                        } else {
                            link = handlers.getGroupLink(groupId);
                            name = handlers.getGroupName(groupId, items);
                        }

                        group = {id: id, name: name, unassigned: unassigned, link: link};

                        groupList.push(group);
                    }

                    scope.groupedItems[group.id] = scope.groupedItems[group.id] || [];

                    if (angular.isDefined(handlers.processingGroup)) {
                        handlers.processingGroup(group, groupList, groupId, items, groupBy, item, handlers, scope);
                    } else {
                        scope.groupedItems[group.id].push({
                            description: handlers.getItemDescription(item),
                            link: handlers.getItemLink(item)
                        })
                    }
                }
            };
        }
    };
}]);

}); });

You can just use filter : 您可以只使用filter

var group = groupList.filter((group) => group.id === id);

EDIT: to return only the element, and not an array, when there is only one match, you can do the following: 编辑:仅返回元素,而不返回数组,只有一个匹配项时,您可以执行以下操作:

var checkSingle = (groups) => groups.length === 1 ? groups[0] : groups;
var group = checkSingle(groupList.filter((group) => group.id === id));

You can _(groupList).groupBy('id').get(id) : 您可以_(groupList).groupBy('id').get(id)

 var groupList = [ { id: 1, name: 'site' }, { id: 2, name: 'test' }, { id: 2, name: 'prod' }, { id: 3, name: 'dev' }, { id: 4, name: 'back' }, { id: 4, name: 'front' }, { id: 5, name: 'sprint' } ]; console.log(_(groupList).groupBy('id').get(2)); console.log(_(groupList).groupBy('id').get(3)); console.log(_(groupList).groupBy('id').get(4)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM