javascript |对象分组 [英] javascript | Object grouping
本文介绍了javascript |对象分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象。它看起来如下:
I have an object. It looks like below:
[
{
"name":"Display",
"group":"Technical detals",
"id":"60",
"value":"4"
},
{
"name":"Manufacturer",
"group":"Manufacturer",
"id":"58",
"value":"Apple"
},
{
"name":"OS",
"group":"Technical detals",
"id":"37",
"value":"Apple iOS"
}
]
我想按组字段对这些数据进行分组并得到这个对象:
I would like to group this data by group field and get this object:
var obj = {
0 = [
{
'group' = 'Technical detals',
'name' = 'Display',
'id' = '60',
'value' = '4'
},
{
'group' = 'Technical detals',
'name' = 'OS',
'id' = '37',
'value' = 'Apple iOS'
}],
1 = [
{
'group' = 'Manufacturer',
'name' = 'Manufacturer',
'id' = '58',
'value' = 'Apple'
}]
}
如何对第一个对象进行分组?
How can I group my first object?
推荐答案
尝试这样的事情:
function groupBy(collection, property) {
var i = 0, val, index,
values = [], result = [];
for (; i < collection.length; i++) {
val = collection[i][property];
index = values.indexOf(val);
if (index > -1)
result[index].push(collection[i]);
else {
values.push(val);
result.push([collection[i]]);
}
}
return result;
}
var obj = groupBy(list, "group");
请记住 Array.prototype.indexOf
在IE8及更早版本中未定义,但有常见的polyfill。
Keep in mind that Array.prototype.indexOf
isn't defined in IE8 and older, but there are common polyfills for that.
这篇关于javascript |对象分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文