对具有相同键的JSON Array的数量求和

Sum quantity of a JSON Array with same key

本文关键字:JSON Array 求和      更新时间:2023-09-26

我有一个javascript对象与数组试图更新"数量"的问题,如果所选项目再次被选择。

我使用的对象是这样定义的:
var Cart = {
    User: 0,
    Store: 0,
    UserID: 0, 
    Deliver: "Entrega",
    Date: "2014-01-01",
    Total: 0,
    ProductsCart: []
};

在ProductsCart中,我创建的数组如下:

Cart.ProductsCart.push({
        "ProductID": id,    //value sent from javascript function 
        "Quantity": Number(Quantity),
        "Price": Price.toFixed(2),
        "Name": name,
        "Desc": desc,
        "Date": date,
        "StoreID": store,
        "UserID": Number(UserID) //Special

我现在面临的问题是,我有一个javascript代码来更新所选产品的数量再次,如果存在它更新的数量,但有时它的工作,有时不是。这是代码

  var temp = {},
            i;
        for (i = Cart.ProductsCart.length - 1; i >= 0; i -= 1) {
            ProductID = Cart.ProductsCart[i].ProductID;
            UserID = Cart.ProductsCart[i].NinoID;
            if (temp.hasOwnProperty(ProductID) && temp.hasOwnProperty(UserID)) {
                Cart.ProductsCart[temp[ProductID]].Quantity += Cart.ProductsCart[i].Quantity;
                //Splice to make one array with updated quantity?
                Cart.ProductsCart.splice(i, 1);
            } else {
                temp[ProductID] = i;
                //I need to identify one product per user and filter the productos by user so Im using that UserID to identify every array per user 
                temp[UserID] = UserID;
            }
        }
        console.log(Cart.ProductsCart);

现在的问题是,有时它会在产品中添加特定的数量,比如

    比萨,数量1
  • 饮料,数量1

但是出于某种原因,对于同一用户或不同的用户,我尝试添加Cake, Quantity 1比萨或饮料的数量发生了变化,蛋糕不再存在。希望你能指点出问题所在提前感谢

编辑 -------------

原始脚本(我的)适用于特定的产品,因为做了一些测试,我发现我使用的是fullcalendar,在特定的日子里每次点击代码都不起作用,但是如果我不点击代码就会起作用。

另一件事是,我使用AJAX带来的产品分类,问题不是得到ID,问题是他们不识别现有的数组

假设你的数组是这样的:

Pizza  4
Cake   3
Pizza  2
Pizza  5
Drink  2

在i = 2时,合并两条Pizza线并将其中一条拼接出来:

Pizza  4
Cake   3
Pizza  7
Drink  2

问题是,现在你的披萨线索引是2,而不是3,但你仍然有temp.Pizza = 3。因此,在i = 0时,您将不正确地合并到索引为3的Drink行。

一种解决方案是在合并时向前而不是向后遍历数组,并且splice()是乘积的后面重复,将第一个留在您记录的索引处。然后确保在拼接之后执行i -= 1这样你就可以再次看到索引了因为其他项已经移动到索引中了

您的问题是在循环中拼接数组,这将导致不希望的效果。你正在迭代数组中的每个元素,但是你在迭代时改变了数组中的元素。你知道这会给你带来什么问题吗?:)

看这个例子,你可以在这个jsfiddle上看到它的演示。

var arr = [
    "one",
    "two",
    "three",
    "four",
    "five"    
];
console.log('Without Splice ...');
for ( var i = 0; i <= arr.length - 1; i++ ) {
    console.log(arr[i]);
}
console.log('With Splice ...');
for ( var i = 0; i <= arr.length - 1; i++ ) {
    console.log(arr[i]);
    arr.splice(i, 1);
}

第一个迭代记录每个项目,正如您所期望的。但是,第二次迭代只记录每一个其他项(1、3、5)。更安全的方法是跟踪要在临时数组中删除的项,然后在迭代完成后根据临时数组中的内容从源中删除这些项。

对不起,我只是没有跟上你的结构。

我要做的是让它有一个Cart对象数组,每个Cart对象都有基本项,比如购物车所属的用户以及这些项的数量:

/**
* @constructor
*/
var Cart = function(){
    var userID;
    var items = [];
    // array of Item
    ...
};
/**
* method for checking if item exists in cart
*/
Cart.prototype.hasItem = function(item){
    for (var i = 0; i < this.items.length; i++){
        if (this.items[i].itemId === item.itemId){
            return true;
        }
    }
    return false;
}

/**
* method for checking if item exists in cart
*/
Cart.prototype.updateItemQty= function(item, difference){
    for (var i = 0; i < this.items.length; i++){
        if (this.items[i].itemId === item.itemId){
            this.items[i].qty += difference;
        }
    }
}

定义项目:

var Item = function() {
    var ItemId;
    var qty;
    ...
}

则保留Cart

的数组
var carts = [];

现在提供了一个方法或函数,用于将商品添加到特定的购物车

function addItem(item, userId){
    for (var i = 0; i < carts.length; i++){
        if (carts[i].userId === userId){
            // add or update item
            if (carts[i].hasItem(item)){
                carts[i].updateItemQty(item, 1);
            } else {
                carts[i].addItem(item);
            }
        } else {
            // add a new cart to carts array first
            // then add the item to that new cart
        }
    }
}