lodash使用技巧--利用lodash将数据分类汇总(笔记)

var result=[
    {
        name:'减1元',
        quantity:1,
        amount:1
    },
    {
        name:'减3元',
        quantity:1,
        amount:3
    },
    {
        name:'减2元',
        quantity:1,
        amount:2
    },
    {
        name:'减4元',
        quantity:1,
        amount:4
    },
    {
        name:'减2元',
        quantity:1,
        amount:2
    }
]
复制代码

将数据进行排序:

var result=_.sortByOrder(result,['name']);
复制代码

排序完的数据显示为:

var result=[
    {
        name:'减1元',
        quantity:1,
        amount:1
    },
    {
        name:'减2元',
        quantity:1,
        amount:2
    },
    {
        name:'减2元',
        quantity:1,
        amount:2
    },
    {
        name:'减3元',
        quantity:1,
        amount:3
    },
    {
        name:'减4元',
        quantity:1,
        amount:4
    }
]
复制代码

根据name值将数据进行分类整理

var grbyResult=_.groupBy(result,'name');
复制代码

整理完的数据格式为:

var grbyResult={
    "减1元":[
        {
            name:'减1元',
            quantity:1,
            amount:1
        }
    ],
    "减2元":[
        {
            name:'减2元',
            quantity:1,
            amount:2
        },
        {
            name:'减2元',
            quantity:1,
            amount:2
        }
    ],
    "减3元":[
        {
            name:'减3元',
            quantity:1,
            amount:3
        }
    ],
    "减4元":[
        {
            name:'减4元',
            quantity:1,
            amount:4
        }
    ]
}
复制代码

汇总数据处理:

var newGry=[];

var amount=0;

var quantity=0;

var name='';

var temVariable={};

_.map(grbyResult,function(item){

    amount=0;

    quantity=0;

    name='';

    _.map(item,function(data){

        amount+=data.amount;
  
        quantity+=data.quantity;
  
        name=data.name;
  
    })

    temVariable={

        name:name,
   
        amount:amount,
   
        quantity:quantity
   
    }

newGry.push(temVariable);
复制代码

})

汇总完的数据:

var result=[
    {
        name:'减1元',
        quantity:1,
        amount:1
    },
    {
        name:'减2元',
        quantity:2,
        amount:4
    },
    {
        name:'减3元',
        quantity:1,
        amount:3
    },
    {
        name:'减4元',
        quantity:1,
        amount:4
    }
]复制代码

你可能感兴趣的:(lodash使用技巧--利用lodash将数据分类汇总(笔记))