通过分组与相同属性的对象数组减少到 [英] reduce array to a by grouping objects with same property

查看:108
本文介绍了通过分组与相同属性的对象数组减少到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的数组,我通过类似的属性值,试图将它们分组。因此,可以说这里是阵列

I have an array of objects and I am trying to group them by similar property value. So lets say here is array

[  
  {  
    "size":"6.5",
    "width":"W"
  },
  {  
    "size":"6.5",
    "width":"M"
  },
  {  
    "size":"7.5",
    "width":"w"
  },
  {  
    "size":"8",
    "width":"M"
  },
  {  
    "size":"8",
    "width":"w"
  }
]

和我试图得到这样的事情

and i am trying to get something like this

[  
  {  
    "size_new":"6.5",
    "width_group":[  
      "W",
      "M"
    ]
  },
  {  
    "size_new":"7.5",
    "width_group":[  
      "M"
    ]
  },
  {  
    "size_new":"8",
    "width_group":[  
      "w",
      "M"
    ]
  }
]

我的js看起来像这样

My js looks like this

var _x = [];

for(var i = 0; i < x.length; i++){
    if(x[i].size == x[i+1].size){
        _x[i] = {
            new_size: x[i].size,
            width_group: [x[i].width,x[i+1].width]
        }
    }
}

下面是我的小提琴
http://jsfiddle.net/sghoush1/ogrqg412/1/

我是pretty确保有可能是一个巨大的大洞在我的逻辑

I am pretty sure that there is probably a giant gaping hole in my logic

推荐答案

一个简单的方法,这样做将是打入几个步骤如下:

One simple way to do this would be to break this into several steps:

var sizeSorter = function(a, b) {return a - b};
var sizes = data.reduce(function(acc, item) {
    (acc[item.size] || (acc[item.size] = [])).push(item.width);
    return acc;
}, {}); //=> {8: ['M', 'W'], '6.5': ['W', 'M'], '7.5': ['W']}
Object.keys(sizes).sort(sizeSorter).map(function(size) {
    return {size_new: size, width_group: sizes[size]};
});

这是排序是必要的,因为钥匙将数组进行排序,像'8'小数字像'6.5'。

That sorting is necessary because the keys will be sorted in Array order, with small numbers like '8' before strings like '6.5'.

这篇关于通过分组与相同属性的对象数组减少到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆