You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS 1中过滤API返回数据:保留最新修改记录

要解决这个问题,我们需要在AngularJS 1中对API返回的数据进行分组过滤,保留每个group+name组合里date_modified最新的条目。下面分两种常用的实现方式来讲解,你可以根据自己的代码结构选择合适的方案。

方案一:在数据服务中处理过滤(推荐,职责分离)

这种方式把数据过滤逻辑封装在Service里,Controller只负责获取处理好的数据,代码更清晰易维护。

假设你的原始services.js是这样的:

angular.module('app').service('DataService', function($http) {
  this.getData = function() {
    return $http.get('/your-api-endpoint')
      .then(function(response) {
        return response.data;
      });
  };
});

修改后的services.js加入过滤逻辑:

angular.module('app').service('DataService', function($http) {
  this.getData = function() {
    return $http.get('/your-api-endpoint')
      .then(function(response) {
        // 调用过滤函数处理原始数据
        return filterLatestEntries(response.data);
      });
  };

  // 私有函数:过滤出每个group+name组合的最新条目
  function filterLatestEntries(rawData) {
    const latestMap = {};

    rawData.forEach(item => {
      // 生成唯一的分组键:用group和name拼接,确保同一组合的条目会被归为一组
      const groupKey = `${item.group}-${item.name}`;
      // 把日期字符串转为Date对象,方便比较大小
      const currentItemDate = new Date(item.date_modified);

      if (!latestMap[groupKey]) {
        // 该分组还没有条目,直接存入
        latestMap[groupKey] = item;
      } else {
        // 比较当前条目和已存条目的日期,保留更新的那个
        const existingItemDate = new Date(latestMap[groupKey].date_modified);
        if (currentItemDate > existingItemDate) {
          latestMap[groupKey] = item;
        }
      }
    });

    // 将对象中的值转为数组,就是我们需要的过滤后数据
    return Object.values(latestMap);
  }
});

然后在Controller里直接获取过滤后的数据:

angular.module('app').controller('DataController', function(DataService) {
  const vm = this;

  DataService.getData().then(function(filteredData) {
    vm.filteredItems = filteredData;
    console.log('过滤后的数据:', filteredData);
  });
});

方案二:自定义AngularJS过滤器(适合多场景复用)

如果需要在多个模板或Controller中复用这个过滤逻辑,可以把它做成一个自定义过滤器:

首先定义过滤器:

angular.module('app').filter('latestEntries', function() {
  return function(inputData) {
    // 非数组直接返回
    if (!Array.isArray(inputData)) return inputData;

    const latestMap = {};
    inputData.forEach(item => {
      const groupKey = `${item.group}-${item.name}`;
      const currentDate = new Date(item.date_modified);

      // 要么该分组无数据,要么当前条目日期更新,就替换
      if (!latestMap[groupKey] || currentDate > new Date(latestMap[groupKey].date_modified)) {
        latestMap[groupKey] = item;
      }
    });

    return Object.values(latestMap);
  };
});

然后在Controller里获取原始数据,在模板中使用过滤器:

angular.module('app').controller('DataController', function(DataService) {
  const vm = this;

  // 获取原始数据
  DataService.getData().then(function(rawData) {
    vm.rawItems = rawData;
  });
});

模板中使用:

<div ng-controller="DataController as vm">
  <h3>过滤后的结果</h3>
  <ul>
    <li ng-repeat="item in vm.rawItems | latestEntries">
      ID: {{item.id}} | Group: {{item.group}} | Name: {{item.name}} | 最后修改: {{item.date_modified}}
    </li>
  </ul>
</div>

关键逻辑说明

  1. 分组键生成:用group和name拼接成唯一字符串,确保同一组合的条目会被分到同一组。
  2. 日期比较:把date_modified转为Date对象,这样可以直接用大于/小于运算符比较时间先后。
  3. 保留最新条目:用对象存储每个分组的最新条目,遍历过程中不断替换为更新的条目,最后把对象转为数组得到结果。

比如如果你的API返回原始数据是:

[
  {id:1, group:"A", name:"Apple", date_modified:"2024-05-01T10:00:00Z"},
  {id:2, group:"A", name:"Apple", date_modified:"2024-05-02T14:00:00Z"},
  {id:3, group:"B", name:"Banana", date_modified:"2024-05-01T09:00:00Z"},
  {id:4, group:"C", name:"Cherry", date_modified:"2024-05-03T16:00:00Z"}
]

过滤后会得到:

[
  {id:2, group:"A", name:"Apple", date_modified:"2024-05-02T14:00:00Z"},
  {id:3, group:"B", name:"Banana", date_modified:"2024-05-01T09:00:00Z"},
  {id:4, group:"C", name:"Cherry", date_modified:"2024-05-03T16:00:00Z"}
]

内容的提问来源于stack exchange,提问作者Codieroot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:46:05