Group js objects by multiple properties

前端 未结 2 1032
甜味超标
甜味超标 2021-01-28 23:46

In the example below I have an array of objects which I group by 2 of their properties (based on https://stackoverflow.com/a/40142591).

        var arr = [{
            


        
相关标签:
2条回答
  • 2021-01-28 23:59

    I believe the below kind of grouping should solve the problem:

    var arr=[{id:1,tags:"main",yearCode:"2018"},{id:2,tags:["main","blue"],yearCode:"2018"},{id:3,tags:["main","green"],yearCode:"2018"},{id:25,tags:["green"],yearCode:"2018"},{id:26,tags:["important"],yearCode:"2017"},{id:29,tags:["important","blue"],yearCode:"2017"},{id:2,tags:["important","green"],yearCode:"2017"}];
    
    var mainFilter = "yearCode";
    var secFilter = "tags";
    
    var result = arr.reduce((map, obj) => {
    
        if (!map[obj[mainFilter]]) map[obj[mainFilter]] = {};
    
        [].concat(obj[secFilter]).forEach(subEl => {
    
            if (!map[obj[mainFilter]][subEl]) map[obj[mainFilter]][subEl] = [];
    
            map[obj[mainFilter]][subEl].push(obj);
    
        });
    
        return map;
    
    }, {});
    
    console.log(result);

    0 讨论(0)
  • 2021-01-29 00:08

    Is this what you are looking for ?

    var arr = [{
                "id": 1,
                "tags": "main",
                "yearCode": "2018"
            }, {
                "id": 2,
                "tags": ["main", "blue"],
                "yearCode": "2018"
            }, {
                "id": 3,
                "tags": ["main", "green"],
                "yearCode": "2018"
            }, {
                "id": 25,
                "tags": ["green"],
                "yearCode": "2018"
            }, {
                "id": 26,
                "tags": ["important"],
                "yearCode": "2017"
            }, {
                "id": 29,
                "tags": ["important", "blue"],
                "yearCode": "2017"
            }, {
                "id": 2,
                "tags": ["important", "green"],
                "yearCode": "2017"
            }];
    
    
            var mainFilter = "yearCode";
            var secFilter = "tags";
            var result = arr.reduce(function(map, obj) 
            {
    
              var f1 = map[obj[mainFilter]] = map[obj[mainFilter]] || {};
    
              if(Object.prototype.toString.call(obj[secFilter]) === '[object Array]')
              {
                var idx;
                for(idx in obj[secFilter])
                {
                  var f2 = f1[obj[secFilter][idx]] = f1[obj[secFilter][idx]] || [];
                  f2.push(obj);             
                }
              }
              else
              {
                var f2 = f1[obj[secFilter]] = f1[obj[secFilter]] || [];
                f2.push(obj);
              }
    
              return map;
            }, Object.create(null));
    
            console.log(JSON.stringify(result));

    0 讨论(0)
提交回复
热议问题