javascript | Object grouping

后端 未结 10 1240
不思量自难忘°
不思量自难忘° 2020-11-27 05:29

I have an object. It looks like below:

[
  {
    \"name\":\"Display\",
    \"group\":\"Technical detals\",
    \"id\":\"60\",
    \"value\":\"4\"
  },
  {
           


        
10条回答
  •  有刺的猬
    2020-11-27 06:01

    If you're using underscore.js in your application then you can simply do the following:

    var groups = _.groupBy(data, 'group'); // data is your initial collection
    

    Or if you prefer not to use any library then you can do it yourself:

    var groups = { };
    data.forEach(function(item){
       var list = groups[item.group];
    
       if(list){
           list.push(item);
       } else{
          groups[item.group] = [item];
       }
    });
    

    You can see both examples in action http://jsfiddle.net/nkVu6/3/

提交回复
热议问题