简体   繁体   中英

How to groupby property in array of objects with lodash?

I am using IE 11

I have an array of objects and I want to group my array of objects by one of the properties called 'program' that I store in an array called 'programs'. I was able to use lodash but I think I used it wrong because the result does not show as grouped.

Here's my code:

var programs = ['ATR','QTR','STR'];


       axios.get("https://my-json-server.typicode.com/isogunro/jsondb/Programs").then(function(response) {
         groupProgram(response.data);
      })
      .catch(function (error) {
        console.log(error+"log");
      });


      function groupProgram(data){
        var newProgram = [];
        _.groupBy(data, function(item){
           for (var i=0; i<programs.length; i++){
             if (programs[i] == item.program){
               newProgram.push(item);
             }
           }
        });
        return newProgram;
      }

I will eventually use the results to generate a table in Vuejs. Here's the pen

Any help would be much appreciated.

Thanks!

You can use Array.reduce ( without lodash ):

 axios.get("https://my-json-server.typicode.com/isogunro/jsondb/Programs").then(function(response) { const groupped = groupProgram(response.data); console.log(groupped); }) .catch(function(error) { console.log(error + "log"); }); function groupProgram(data) { const result = data.reduce((acc, curr) => { acc[curr.program].push(curr); return acc; }, { 'ATR': [], 'QTR': [], 'STR': [], }); return result; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script> 

The way you've written your code, you are using the groupBy function as a forEach function and manipulating data yourself (which is ok if you use forEach). To use the groupBy functionality, you want something more like:

var programs = ['ATR','QTR','STR'];


axios.get("https://my-json-server.typicode.com/isogunro/jsondb/Programs").then(function(response) {
     var groupedData = groupProgram(response.data);
    console.log(groupedData);
})
.catch(function (error) {
    console.log(error+" log");
});


function groupProgram(data){
    return _.groupBy(data, 'program');
}

Of course, to act on it, you usually would chain it with other functions. You might find it easier to move to the more "modern" ngRx approach using reduce, map, and similar functions, depending upon what you want to accomplish with the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM