0

I have a JSON array:

[{ id: 1, client: "Microsoft" },{ id: 2, client: "Microsoft" },{ id: 3, client: "Apple" }]

and I'd like to group it by "client", but I'm having difficulty with this in javascript. In PHP i'd typically do something like this:

$group = array();

foreach ($array as $item) {

    $group[ $item['client'] ] = $item;

}

return $group;

But this method totally wont't work in javascript on a multidimensional array

var group = [];

for ( i=0 ... ) {

  var client = array[i].client;

  group[ client ].push( array[i] );

}

How would I go about grouping the above array into something like this:

[{ "Microsoft": [{...}], "Apple":[{...}] }]

or even

[{ client: "Microsoft", "items": [{...}] }, { client: "Apple", items: [{...}] }]

4

1 回答 1

6

为此,您需要一个对象,而不是数组:

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
于 2013-05-23T20:11:42.943 回答