基于ID的JavaScript过滤器数据

时间:2018-11-28 01:39:12

标签: javascript arrays angularjs json object

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

 {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函数适合于此?

3 个答案:

答案 0 :(得分:1)

let yourDesiredContentId = 481;
let result = array.filter(el => el.courseContentId === yourDesiredContentId);

答案 1 :(得分: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>

答案 2 :(得分:0)

不确定是否有简单的方法可以做到这一点。无论如何,请尝试以下方法:

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;
  }, []);
}