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: [{...}] }]
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
Share Improve this question asked May 23, 2013 at 20:07 neilneil 3872 gold badges5 silver badges13 bronze badges[{ client: "Microsoft", "items": [{...}] }, { client: "Apple", items: [{...}] }]
1 Answer
Reset to default 6You need an object for that, not an array:
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);
It's important to keep in mind that the resulting object will contain references to the objects from the original array. For example:
array[0].id = 100;
group.Microsoft[0].id; // 100