[英]Remove n items from an array with object based on property name
我在这里有这个数组:
result = [{ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"} , {ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"}];
等等。
到目前为止,我的数组刚好包含5个类别中的20个项目-因此每个类别都包含4个项目。
我想诉诸我的数组,使其包含:
2个类别,= “常规”的项目
根据上述规则,使我的数组仅包含15个项目的最佳方法是什么。
PS:当然,在重新排序后的新阵列中将保留5个项目。
我曾考虑过遍历该数组并使用IF / Else语句求助一个新语句,但我希望看到执行此操作的最佳和最简单方法。
最干净的imo将使用Array.filter()
和计数器来获取所需的确切类别。
// these are the categories and their allowed maxCounts
var counts = {
"Vegetables": {maxCount: 4, count: 0},
"Fingerfood": {maxCount: 3, count: 0},
//...
};
// filtered is the reduced array containing just the ones you need
var filtered = result.filter(function(_item) {
var c = counts[_item.category];
// include only if allowed as per counts
if(c && c.count < c.maxCount) { c.count++; return true; }
return false;
});
PS:
counts
类别名称应与result
类别名称匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.