最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript push array item to named index - Stack Overflow

programmeradmin1浏览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: [{...}] }]

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: [{...}] }]

Share Improve this question asked May 23, 2013 at 20:07 neilneil 3872 gold badges5 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You 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
发布评论

评论列表(0)

  1. 暂无评论