How to group an array of objects by key

后端 未结 24 3435
后悔当初
后悔当初 2020-11-21 05:13

Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav

24条回答
  •  無奈伤痛
    2020-11-21 05:30

    Building on the answer by @Jonas_Wilms if you do not want to type in all your fields:

        var result = {};
    
        for ( let { first_field, ...fields } of your_data ) 
        { 
           result[first_field] = result[first_field] || [];
           result[first_field].push({ ...fields }); 
        }
    
    

    I didn't make any benchmark but I believe using a for loop would be more efficient than anything suggested in this answer as well.

提交回复
热议问题