在javascript数组中合并重复项 [英] merging duplicates in javascript array

查看:74
本文介绍了在javascript数组中合并重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在JS中有如下数组

if i have a an array like below in 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'
 }]

我如何将其转换为下面的样子

how do i conver it to look like below

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合并重复项

basically looking to merge duplicates based on SKU

推荐答案

纯JS;快速计算器;

Pure JS; Fast calculator;

<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>

这篇关于在javascript数组中合并重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆