Javascript 对嵌套数组进行分组
我在Javascript 对嵌套数组进行分组,javascript,jquery,d3.js,Javascript,Jquery,D3.js,我在d3.js中有一个由nest方法生成的数组,有人能推荐一种javascript/jQuery方法,按类别对值属性中的对象进行分组吗 var data = [ { "key": "0", "values": [ { "category": "phone", "brand": "Sony", "brand_id": "0", "name": "item A", "id": "551",
d3.js
中有一个由nest
方法生成的数组,有人能推荐一种javascript/jQuery方法,按类别对值
属性中的对象进行分组吗
var data = [
{
"key": "0",
"values": [
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item A",
"id": "551",
"point": "600"
},
{
"category": "software",
"brand": "Sony",
"brand_id": "0",
"name": "item D",
"id": "51",
"point": "800"
},
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item E",
"id": "52",
"point": "1800"
}
]
},
{
"key": "0",
"values": [
{
"category": "software",
"brand": "Microsoft",
"brand_id": "1",
"name": "item B",
"id": "54",
"point": "800"
},
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "1",
"name": "item B",
"id": "60",
"point": "200"
},
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "1",
"name": "item T",
"id": "30",
"point": "600"
},
{
"category": "software",
"brand": "Microsoft",
"brand_id": "1",
"name": "item N",
"id": "90",
"point": "500"
}
]
}
];
下面是一个期望的结果:
[
{
"key": "0",
"values": [
{
"phone": [
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item A",
"id": "551",
"point": "600"
},
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item E",
"id": "52",
"point": "1800"
}
],
"software": [
{
"category": "software",
"brand": "Sony",
"brand_id": "0",
"name": "item D",
"id": "51",
"point": "800"
}
]
}
]
},
{
"key": "0",
"values": [
{
"phone": [
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "0",
"name": "item B",
"id": "80",
"point": "54"
},
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "0",
"name": "item D",
"id": "52",
"point": "1800"
}
],
"software": [
{
"category": "software",
"brand": "Microsoft",
"brand_id": "0",
"name": "item G",
"id": "41",
"point": "800"
},
{
"category": "software",
"brand": "Microsoft",
"brand_id": "0",
"name": "item L",
"id": "42",
"point": "900"
}
]
}
]
}
]
以下代码不起作用。我想这是因为grouped[t.category]=[]
是在每个循环中定义的。上一项将被最后一项覆盖。如果我没有定义它,我会得到一个grouped[t.category]
undefined错误:
grouped = {};
data.forEach(function(d){
d.values.map(function(t){
grouped[t.category] = [];
grouped[t.category].push({name:t.name,tid:t.id,point:parseInt(t.point)});
})
})
试试这个
var grouped;
data.forEach(function(d) {
grouped = {};
d.values.forEach(function(t) {
if (!grouped[t.category]) {
grouped[t.category] = [];
}
grouped[t.category].push({
name: t.name,
tid: t.id,
point: parseInt(t.point)
});
})
d.values = grouped;
});
您可以尝试以下方法:
您可以使用或类似的库来解决此问题
_.map(data, function(x){
return _.assign({}, x, {values: _.groupBy(x.values, 'category')})
})
我熟悉:
希望它能帮助你
_.map(data, function(x){
return _.assign({}, x, {values: _.groupBy(x.values, 'category')})
})
var desireResult = _.map(data, function(obj){
obj.values = _.groupBy(obj.values, 'category');
return obj;
});