简体   繁体   English

筛选数组并创建一个新数组

[英]Filter an array and create a new array

I have a very simple requirement for filter some objects from a larger array and create a sub-array. 我有一个非常简单的要求,即从较大的数组中筛选出一些对象并创建子数组。 Right now, I'm doing it as follows, but I'm wondering whether I could do inline and avoid the for-each. 现在,我正在按照以下步骤进行操作,但是我想知道是否可以内联并避免for-each。

        var branches = $filter('filter')(vm.locations, { 'fkLocationTypeId': 5 });
        vm.branchList = [];
        angular.forEach(branches, function (obj) {
            vm.branchList.push({ id: obj.Id,  label: obj.locationDisplayName });
        });

Since you want to both filter the array and modify the retained items, you can use filter() in combination with map() , both native array methods 由于您既要过滤数组又要修改保留项,因此可以将filter()map()结合使用,这两种本机数组方法

vm.branchList = vm.locations
  .filter(function(location) {
    return location.fkLocationTypeId === 5;
  })
  .map(function(location) {
    return {
      id: location.Id,
      label: location.locationDisplayName
    };
  });

If you want to avoid iterating over the array twice you can use the reduce() method to perform both the filtering and mapping at the same time 如果要避免两次遍历数组,可以使用reduce()方法同时执行过滤和映射

vm.branchList = vm.locations
  .reduce(function(builtList, location) {
    if (location.fkLocationTypeId === 5) {
      return builtList.concat({
        id: location.Id,
        label: location.locationDisplayName
      });
    }
    return builtList;
  }, []);

I don't think there's much wrong with your use of forEach , but you could replace it by a map operation on the filtered set. 我认为您使用forEach并没有多大问题,但是您可以通过对过滤后的集合执行map操作来替换它。

Personally, I'd use reduce to combine both filter and map operations in one loop, but you'd probably only start seeing a performance increase when you're filtering very large sets of data. 就个人而言,我将使用reducefiltermap操作组合在一个循环中,但是当您过滤大量数据时,您可能只会开始看到性能的提高。

To combine the two in one reducer: 要将两者合二为一的减速器:

 const locToObj = loc => ({ id: loc.Id, label: loc.locationDisplayName }); const branchReducer = (acc, loc) => loc.fkLocationTypeId === 5 ? (acc.push(locToObj(loc)), acc) : acc const branches = vm.locations.reduce(branchReducer, []); 

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

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