合并javascript数组中的重复项

时间:2015-09-17 12:59:40

标签: javascript arrays

如果我在JS中有一个如下所示的数组

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'
 }]

我如何将其转换为如下所示

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的重复项

4 个答案:

答案 0 :(得分:1)

你可以使用关联数组:

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

答案 1 :(得分:1)

您可以使用Array.prototype.forEach()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

var result = []
var temp = [];
lineitems.forEach(function (element, index, array) {
    if (temp[element.SKU] === undefined)
        temp[element.SKU] = element;
    else
        temp[element.SKU].quantity += element.quantity;
});
for (var items in temp){
    result.push(temp[items]);
}

希望它有用

答案 2 :(得分:0)

使用lodash是管理集合的快捷方式:

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

答案 3 :(得分:0)

纯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>
&#13;
&#13;
&#13;