【问题标题】:Javascript filter data based on the IDJavascript 根据 ID 过滤数据
【发布时间】:2019-04-29 20:25:03
【问题描述】:

我有一个包含这些数据的对象。

 {id: 1864,
 courseContentId: 481,
 fileName: GymMembership.jpg
 }
 {id: 1865,
 courseContentId: 481,
 fileName: Field.jpg
 }
 {id: 1866,
 courseContentId: 482,
 fileName: Track.jpg
 }

我想通过创建一个新对象在基于 courseContentId 的视图上分别显示它们,这是我想要的输出。

 {id: 1864,
 courseContentId: 481,
 fileName: GymMembership.jpg
 }
 {id: 1865,
 courseContentId: 481,
 fileName: Field.jpg
 }

 {id: 1866,
 courseContentId: 482,
 fileName: Track.jpg
 }

什么样的javascript函数适合这个?

【问题讨论】:

  • 你在标题中回答了你的问题......filter!
  • @slider 是的,但在我的情况下,我需要根据 courseContentId 分别显示它们。它类似于唯一唯一的显示,但我需要分别显示具有相同 courseContentId 的所有内容。

标签: javascript arrays angularjs json object


【解决方案1】:

只需使用_.GroupBy,而不是应用多个过滤器。

courses = [{id: 1864,
 courseContentId: 481,
 fileName: 'GymMembership.jpg'
 },
 {id: 1865,
 courseContentId: 481,
 fileName: 'Field.jpg'
 },
 {id: 1866,
 courseContentId: 482,
 fileName: 'Track.jpg'
 }]
 
var grouped = _.groupBy(courses, function(course) {
  return course.courseContentId;
});
console.log("Grouped")
console.log(grouped);
console.log("Filter by 481")
console.log(grouped["481"]);
console.log("Filter by 482")
console.log(grouped["482"]);
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"></script>

【讨论】:

  • 谢谢。几乎,但我不应该手动输入 ID。 javascript中的什么函数可以获得所有相似的属性。
  • 如果我错了,请纠正我,你想要类似courseContentId 的分组数组。我对吗?如果是,那么我已经更新了相同的答案。您可以找到第一个控制台输出,否则请告诉我。
  • 谢谢。但我还有一个问题。使用 group by 后如何保留原始索引号?
  • @TheNinja,您可以在数组中显式附加索引以对其进行排序,也可以按分组数组的“键”进行排序。让我知道获得相同索引的原因是什么。
【解决方案2】:
let yourDesiredContentId = 481;
let result = array.filter(el => el.courseContentId === yourDesiredContentId);

【讨论】:

    【解决方案3】:

    不确定是否有简单的方法可以做到这一点。不管怎样,试试这个:

    var test = [{
        id: 1864,
        courseContentId: 481,
        fileName: 'GymMembership.jpg'
      },
      {
        id: 1865,
        courseContentId: 481,
        fileName: 'Field.jpg'
      },
      {
        id: 1866,
        courseContentId: 482,
        fileName: 'Track.jpg'
      }
    ];
    
    console.log(filter(test, 'courseContentId', 481));
    
    function filter(arr, key, value) {
      return arr.reduce((data, item) => {
        if (item[key] == value) data.push(item);
        return data;
      }, []);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2021-09-16
      • 2018-04-29
      • 1970-01-01
      相关资源
      最近更新 更多