通过将具有相同属性的对象分组来将数组缩减为 a [英] reduce array to a by grouping objects with same property

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

问题描述

我有一个对象数组,我正在尝试按相似的属性值对它们进行分组.所以让我们说这里是数组

<预><代码>[{"尺寸":"6.5","宽度":"W"},{"尺寸":"6.5","宽度":"M"},{"尺寸":"7.5",宽度":w"},{"尺寸":"8","宽度":"M"},{"尺寸":"8",宽度":w"}]

我正试图得到这样的东西

<预><代码>[{"size_new":"6.5",宽度组":["W",米"]},{"size_new":"7.5",宽度组":[米"]},{"size_new":"8",宽度组":["w",米"]}]

我的js看起来像这样

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/

我很确定我的逻辑中可能有一个巨大的漏洞

解决方案

一种简单的方法是将其分解为几个步骤:

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

这种排序是必要的,因为键将按数组顺序排序,在像 '6.5' 这样的字符串之前有像 '8' 这样的小数字.

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"
    ]
  }
]

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]
        }
    }
}

Here is my fiddle http://jsfiddle.net/sghoush1/ogrqg412/1/

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

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

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

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