我有一个JSON数组:
[{id:1,客户端:“Microsoft”},{id:2,客户端:“Microsoft” },{id:3,client:“Apple”}]
我想用“客户端”对它进行分组,但我在javascript中遇到此问题。在PHP中,我通常会这样做:
$group = array();
foreach ($array as $item) {
$group[ $item['client'] ] = $item;
}
return $group;
但是这种方法完全不适用于多维数组的javascript
var group = [];
for ( i=0 ... ) {
var client = array[i].client;
group[ client ].push( array[i] );
}
我如何将上述数组分组为:
[{“Microsoft”:[{...}],“Apple”:[{...}]}]
甚至
[{client:“Microsoft”,“items”:[{...}]},{client:“Apple”,items:[{...}]}]
答案 0 :(得分:5)
你需要一个对象,而不是一个数组:
var array = [{ id: 1, client: "Microsoft" },{ id: 2, client: "Microsoft" },{ id: 3, client: "Apple" }];
var group = {};
for (var i=0; i<array.length; i++) {
var client = array[i].client;
group[client] = group[client] || []; // create array for client if needed
group[client].push(array[i]);
}
console.log(group);
请务必记住,生成的对象将包含引用到原始数组中的对象。例如:
array[0].id = 100;
group.Microsoft[0].id; // 100