JavaScript - 通过计数查找对象数组中的唯一值并创建新的对象数组

标签 javascript arrays object filtering

我有一个对象数组,如下所示:

var arr =[
 {
  price:20,
  rule:a
 },
 {
  price:10,
  rule:b
 },
 {
  price:5,
  rule:a
 },
 {
  price:50,
  rule:b
 },
 {
  price:70,
  rule:b
 }
]

我想从中提取一个对象数组,如下所示:

var filteredArr = [
 {
  rule:a,
  countOfRule:2,
  minPriceForThisRule:5
 },
 {
  rule:b,
  countOfRule:3,
  minPriceForThisRule:10
 }
]

这意味着:

1) 我想创建一个没有的新数组。对象的唯一编号。第一个数组“arr”中的规则

2) 需要计算唯一规则重复次数并将其添加为新数组对象中的属性 - 给出“countOfRule”

3) 查找唯一规则类别中的最低价格 - 以“minPriceForThisRule”形式给出

我已经阅读了类似的答案,并且只能得到前两个条件,而且这也不是我需要的格式。

我尝试过的,引用SO上的链接:

var ff = {},e;
for (var i = 0,l=arr.length; i < l; i++) {
   e = arr[i];
   ff[e.rule] = (ff[e.rule] || 0) + 1;
}

但这只给出了一个对象

{
 a : 2,
 b: 3
}

最佳答案

您可以使用forEach来做到这一点和 thisArg 可选参数。

var arr = [{"price":20,"rule":"a"},{"price":10,"rule":"b"},{"price":5,"rule":"a"},{"price":50,"rule":"b"},{"price":70,"rule":"b"}], 
    r = [];

arr.forEach(function(e) {
  if(!this[e.rule]) {
    this[e.rule] = {rule: e.rule, countOfRule: 0, minPriceForThisRule: e.price}
    r.push(this[e.rule]);
  }
  this[e.rule].countOfRule++;
  if(this[e.rule].minPriceForThisRule > e.price) this[e.rule].minPriceForThisRule = e.price;
}, {});

console.log(r)

关于JavaScript - 通过计数查找对象数组中的唯一值并创建新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37812090/

相关文章:

javascript - 不使用 event.preventDefault 阻止 html5 表单提交

javascript - 如何在 Javascript 中获取数组中所有相同类型的对象?

object - 轨道 4 : Correct way to create objects from other model from the controller

python - 收到错误 AttributeError : '_tkinter.tkapp' object has no attribute 'getitems'

c# - 为什么 int 不能为空?可为空的 int(int?)如何在 C# 中工作?

javascript - React HOC 回调不适用于默认 Prop

javascript - SlideUp 和 SlideDown jQuery

javascript - JS : What's the difference between =+ and +=

javascript - 如何同时遍历多维数组中的每个数组

arrays - 数组元素赋值的奇怪行为