码迷,mamicode.com
首页 > 其他好文 > 详细

运用汇总

时间:2019-05-14 13:03:33      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:for   index   数组   参数   turn   grep   ==   用法   price   

1、将数组对象arr按照num倒序排序。

var arr = [
    {name:‘A‘,num:4},
    {name:‘G‘,num:3},
    {name:‘V‘,num:5},
    {name:‘A‘,num:2},
    {name:‘X‘,num:9},
    {name:‘R‘,num:6},
    {name:‘N‘,num:undefined},
]
function compare(property){  // 该函数用来接收对象属性名
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value2 - value1;
    }
}        
arr.sort(compare(‘num‘));// 用法:sort方法接收这个函数作为参数

2、$.grep 处理数据

(1)数据

data.data = [
{
BUY_PRICE: -500,
BUY_QTY: 30,
GOODS_ID: 292,
SKU_ID: 52,
SKU_NAME: "液氯(1)",
SKU_PRICE: 0,
delivery_fee: 0,
goods_sku_price: 950
},
{
BUY_PRICE: -500,
BUY_QTY: 52,
GOODS_ID: 292,
SKU_ID: 20,
SKU_NAME: "液氯(瓶车)",
SKU_PRICE: 0,
delivery_fee: 0,
goods_sku_price: 950
},
{
BUY_PRICE: -500,
BUY_QTY: 21,
GOODS_ID: 292,
SKU_ID: 52,
SKU_NAME: "液氯(1)",
SKU_PRICE: 0,
delivery_fee: 0,
goods_sku_price: 950
},
{
BUY_PRICE: -500,
BUY_QTY: 30,
GOODS_ID: 292,
SKU_ID: 20,
SKU_NAME: "液氯(瓶车)",
SKU_PRICE: 0,
delivery_fee: 0,
goods_sku_price: 950
},
{
BUY_PRICE: -500,
BUY_QTY: 21,
GOODS_ID: 292,
SKU_ID: 21,
SKU_NAME: "液氯(2)",
SKU_PRICE: 0,
delivery_fee: 0,
goods_sku_price: 950
}
]

(2)处理

var arr = res.data.data;
var all = [];
var nameArrO = [],nameArrN = [];

for(var i=0;i<arr.length;i++){
   nameArrO.push(arr[i].SKU_ID)
}
for(var i = 0; i < nameArrO.length; i++){
	if(nameArrN.indexOf(nameArrO[i]) == -1){
		nameArrN.push(nameArrO[i]);
	}
}
for(var i = 0; i < nameArrN.length; i++){
  var item = $.grep(arr, function(num,index) {
	  return ( num.SKU_ID == nameArrN[i] );
  });
  var totalNum = 0,totalPrice = 0;

  for(var j=0;j<item.length;j++){
	  totalNum+=item[j].BUY_QTY;
	  totalPrice+=item[j].BUY_QTY*(item[j].BUY_PRICE+item[j].delivery_fee1);
  }
  all.push({
	  name:item[0].SKU_NAME,
	  id:item[0].SKU_ID,
	  totalNum:totalNum,
	  totalPrice:totalPrice,
	  data:item
  })
}

 (3)处理后返回的数据

all =  [
    {
        data: [
            {
               ...data.data
            },
        ]
        id: 20,
        name: "液氯(瓶车)",
        totalNum: 72,
        totalPrice: -6780,
    },
    {
        data: [
            {
               ...data.data
            },
        ]
        id: 52,
        name: "液氯(1)",
        totalNum: 72,
        totalPrice: -6780,
    },
    {
        data: [
            {
               ...data.data
            },
        ]
        id: 21,
        name: "液氯(2)",
        totalNum: 72,
        totalPrice: -6780,
    }
]

  

 

  

 

运用汇总

标签:for   index   数组   参数   turn   grep   ==   用法   price   

原文地址:https://www.cnblogs.com/panpan-1023/p/10861131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!