Search code examples
lodash

Nested arrays to call map and shorten repeated maps for single object omit property


I have a situation here where I want to omit the nested maps and get it done in one liner . Can it be done using chain or any other ways .

 self.workorder.tasklist = _.map(self.workorder.tasklists, function (tasklist) {
                    tasklist.tasklistGroups = _.map(tasklist.tasklistGroups, function (tasklistGroup, tgKey) {
                        tasklistGroup.tasklistItems = _.map(tasklistGroup.tasklistItems, function (taskListItem, tKey) {
                            taskListItem = _.omit(taskListItem, ["open"]);
                            return taskListItem;
                        });
                        return tasklistGroup;
                    });
                    return tasklist;
                });

I don't want so many nested map calls .


Solution

  • Because you are modifying your items in place I would say this is possible:

      _.chain(self.workorder.tasklists).map(function(tasklist) {
        return tasklist.tasklistGroups;
      }).flatten().map(function(group) {
        return group.tasklistItems
      }).flatten().forEach(function(item) {
        delete item.open;
      }).value();
    

    Jsfiddle

    The idea is to flatten your array to last level (level of items) and then modify them using forEach.