在Coffeescript中,我将如何通过一个属性对对象数组进行分组
In Coffeescript, how would I group an array of objects by one property?
假设我有一个对象数组,如下所示:
var array = [
{name:"aaa", height:"20"},
{name:"bbb", height:"100"},
{name:"ccc", height:"20"},
{name:"ddd", height:"20"},
{name:"eee", height:"100"},
]
在这种情况下,我想按高度对其进行分组,所以我最终得到了一个不同的数组,它有组名,然后是该组中的每个项目,如下所示:
var grouped_by_height = [
[{name:"aaa", height:"20"}, {name:"ccc", height:"20"}, {name:"ddd", height:"20"}],
[{name:"bbb", height:"100"}, {name:"eee", height:"100"}]
]
我在JS/jQuery中写了一个很长的解决方案,但我想知道是否有一种快速简单的方法可以做到这一点,那就是Coffeescapet。
array = [
{name:"aaa", height:"20"},
{name:"bbb", height:"100"},
{name:"ccc", height:"20"},
{name:"ddd", height:"20"},
{name:"eee", height:"100"},
]
# unique heights
uniq = array.reduce (memo, el) ->
memo.push(el.height) if memo.indexOf(el.height) is -1
memo
, []
# output grouped by height
out = [[obj for obj in array when obj.height is height][0] for height in uniq][0]
我不认为CoffeeScript中有什么特别的东西可以帮助你(或者至少没有什么可以解决困难的部分)。我可能会用Array.prototype.reduce
来做这样的重物:
group_by_height = (groups, obj) ->
groups[obj.height] ?= [ ]
groups[obj.height].push(obj)
groups
grouped_obj = array.reduce(group_by_height, { })
grouped_by_height = (v for k, v of grouped_obj)
不过,这并不能保证grouped_by_height
中有任何特定的顺序,但可以通过添加一个排序步骤来解决这个问题:
by_height = (a, b) -> +a[0].height - +b[0].height
group_by_height = (v for k, v of grouped_obj).sort(by_height)
您将对数组数组进行排序,使a
和b
成为数组,因此[0]
将查看第一个元素。一元+
运算符用于将字符串高度转换为数字高度,以便它们按照您可能期望的方式进行比较。
这就是我能够想到的。正如穆所说的,咖啡脚本并没有什么魔力,但有一些内置的东西可以帮助它。唯一的问题是,编译后的js版本最终会比用纯js编写的版本更长。
groupByKey = (array, key) ->
grouped = {}
for obj in array
grouped[obj[key]] ?= []
grouped[obj[key]].push obj
Object.keys(grouped).map (group) ->
grouped[group]
自己试试:
array = [
{
name: 'aaa'
height: '20'
}
{
name: 'bbb'
height: '100'
}
{
name: 'ccc'
height: '20'
}
{
name: 'ddd'
height: '20'
}
{
name: 'eee'
height: '100'
}
]
groupByKey = (array, key) ->
grouped = {}
for obj in array
grouped[obj[key]] ?= []
grouped[obj[key]].push obj
Object.keys(grouped).map (group) ->
grouped[group]
console.log groupByKey(array, 'height')
输出为:
[
[
{
name: 'aaa',
height: '20'
},
{
name: 'ccc',
height: '20'
},
{
name: 'ddd',
height: '20'
}
],
[
{
name: 'bbb',
height: '100'
},
{
name: 'eee',
height: '100'
}
]
]
相关文章:
- 如何从对象的原型方法访问JavaScript对象属性
- 如何将数组项添加到对象属性中
- 设置嵌套对象属性的更好方法
- JavaScript管理具有重复属性名称的对象属性
- 如何使用element.myobj.prop等具有对象属性的元素
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 如何在AngularJS工厂中正确声明对象属性
- 如何使用object.assign()从其他对象引用基本对象属性
- 使用XPath样式访问Javascript JSON对象属性
- 将javascript对象(属性+值)合并到一个对象中
- 数组:使对象属性成为数组键
- 无法从JavaScript中的函数调用对象属性
- Google Closure Advanced |无法识别对象属性|动态属性
- Javascript从匿名函数访问外部对象属性
- 从函数更改对象属性
- 如何从字符串变量访问对象属性
- 从嵌套对象属性中获取排除某个值的最高值
- 在Aurelia computeds中,当设置依赖关系时,如何声明对对象属性的依赖关系
- 传递数量不确定的可能嵌套的对象属性