2015-09-17 22 views
0

在合併重複的,如果我有一個數組像下面的JSJavaScript數組

lineitems : [{ 
    quantity : 1, 
    unitPrice : 10.00, 
    unitPriceLessTax: 8.33, 
    SKU: 'SKU123456', 
    productName: 'Blue T-Shirt' 
}, 
{ 
    quantity : 1, 
    unitPrice : 10.00, 
    unitPriceLessTax: 8.33, 
    SKU: 'SKU123456', 
    productName: 'Blue T-Shirt' 
}, 
{ 
    quantity : 1, 
    unitPrice : 48.00, 
    unitPriceLessTax: 40.00, 
    SKU: 'SKU78910', 
    productName: 'Red Shoes' 
}] 

我如何CONVER它看起來像下面

lineitems : [{ 
    quantity : 2, 
    unitPrice : 10.00, 
    unitPriceLessTax: 8.33, 
    SKU: 'SKU123456', 
    productName: 'Blue T-Shirt' 
}, 
{ 
    quantity : 1, 
    unitPrice : 48.00, 
    unitPriceLessTax: 40.00, 
    SKU: 'SKU78910', 
    productName: 'Red Shoes' 
}] 

基本上尋求合併基於SKU

重複
+0

請你要比較的形成你的更好的可視性 – Saar

+0

代碼? –

回答

0

Pu re JS;快速計算器;

<script> 
 
    var lineItems = [{ 
 
    quantity : 1, 
 
    unitPrice : 10.00, 
 
    unitPriceLessTax: 8.33, 
 
    SKU: 'SKU123456', 
 
    productName: 'Blue T-Shirt' 
 
}, 
 
{ 
 
    quantity : 1, 
 
    unitPrice : 10.00, 
 
    unitPriceLessTax: 8.33, 
 
    SKU: 'SKU123456', 
 
    productName: 'Blue T-Shirt' 
 
}, 
 
{ 
 
    quantity : 1, 
 
    unitPrice : 48.00, 
 
    unitPriceLessTax: 40.00, 
 
    SKU: 'SKU78910', 
 
    productName: 'Red Shoes' 
 
}]; 
 

 
var nl =[], i=0; 
 
var collapse = function() 
 
{ 
 
    if (lineItems.length<=i) return; 
 
    if (nl[lineItems[i].SKU]) 
 
    { 
 
     nl[lineItems[i].SKU].quantity+=lineItems[i].quantity; 
 
    } 
 
    else nl[lineItems[i].SKU]=lineItems[i]; 
 
    i++; 
 
    //lineItems.splice(0,1); 
 
    collapse(); 
 
}; 
 
collapse(); 
 
console.log(nl); 
 
var newLineItems = Object.keys(nl).map(function (key) {return nl[key]}); 
 
console.log(newLineItems); 
 
console.log('new line items'); 
 
console.log(lineItems); 
 
</script>

+0

謝謝你這是完美 –

+0

嗨李奧,你能幫我解決我面臨的問題嗎?基本上當我破壞代碼原始數組得到overritten的值,所以我是assumin ghtis是因爲我們正在使用「返回nl [鍵]」我怎麼能過來的問題,其中原始值的「lineItems」沒有觸及,但只有「 N1「 –

+0

我已經嘗試將lineItems分配給另一個數組,並使用相同的但它仍然更新原始值。我必須對新的原始數組進行驗證。感謝您的幫助 –

1

可以使用關聯數組:

var newLineItems = new Array(); 
$.each(lineItems, function (index) { 
    if (newLineItems[this.SKU]) 
     newLineItems[this.SKU].quantity += this.quantity; 
    else 
     newLineItems[this.SKU] = this; 
}); 
+0

使用一個對象,而不是一個數組。 – Andy

0

使用lodash是一個快速的方法來管理你的集合:

result = _.uniq(lineitems, "SKU"); 
+0

謝謝,但這不會總結數量 –