我有一个包含这些数据的对象。
{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函数适用于此?
最佳答案
只需使用_.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>