从数组javascript中的对象中删除和替换项

时间:2022-08-26 14:07:53

I have read and tried all of the posts of SO on this subject, but for some reason none of the answers are providing the desired effect.

我已阅读并尝试过关于此主题的所有SO帖子,但由于某些原因,没有一个答案能够提供所需的效果。

I have written a shopping basket program and once the user clicks the'Buy now' button I wish to make POST request containing an object with the users order.

我编写了一个购物篮程序,一旦用户点击“立即购买”按钮,我希望发出包含用户订单对象的POST请求。

Problem

The user has the option to purchase three different items. Each time the user clicks on an item, which is a html input box, to increase the amount they wish to purchase I want to update the object to only contain the latest amount chosen.

用户可以选择购买三种不同的商品。每次用户点击一个项目(一个html输入框),增加他们想要购买的金额时,我想更新该对象只包含所选的最新金额。

In its simplest format the basket, when initiated, looks like this :

在最简单的格式中,篮子在启动时看起来像这样:

 var basket = {items:[
                    {item:"Trousers", quantity:1, cost:"10"},
                    {item:"Trainers", quantity:1, cost:"5"},
                    {item:"Jacket", quantity:1, cost:"30"}
                ]}

Each time the user clicks the input button I wish for the basket to be updated so if the user clicked to increase the jacket to a quantity of 3, and the trousers to 4 I want the object to look like this:

每次用户点击输入按钮我希望更新篮子,所以如果用户点击将夹克增加到3,而裤子到4,我希望对象看起来像这样:

 var basket = {items:[
                        {item:"Trousers", quantity:4, cost:"40"},
                        {item:"Trainers", quantity:1, cost:"5"},
                        {item:"Jacket", quantity:3, cost:"90"}
                    ]}

Then if a user decides to reduce the number of trousers by 1, to 3, I would want the basket.items object to look like this:

然后,如果用户决定将裤子数量减少1,为3,我希望basket.items对象看起来像这样:

 var basket = {items:[
                            {item:"Trousers", quantity:3, cost:"30"},
                            {item:"Trainers", quantity:1, cost:"5"},
                            {item:"Jacket", quantity:3, cost:"90"}
                        ]}

I have written the code for all the calculations etc. so this is not the issue but the issue is to update basket.items to only contain the three items listed above at once, with the latest data.

我已经为所有计算等编写了代码,所以这不是问题,但问题是将basket.items更新为仅包含上面列出的三个项目,并包含最新数据。

I cannot use the filter method as this needs to work in older versions of IE. I have tried all solutions listed in this and this along with many more but none of these answers are providing the solution I am looking for.

我无法使用过滤器方法,因为这需要在旧版本的IE中工作。我已经尝试了本次和此列出的所有解决方案以及更多,但这些答案都没有提供我正在寻找的解决方案。

Let me know if any further information is required.

如果需要任何进一步的信息,请与我们联系。

4 个解决方案

#1


2  

try this:

var basket = {
    items: [

    {
        item: "Trousers",
        quantity: 1,
        cost: "10"
    }, {
        item: "Trainers",
        quantity: 1,
        cost: "5"
    }, {
        item: "Jacket",
        quantity: 1,
        cost: "30"
    }]
};

function updateBasket(item) {
    basket.items = basket.items.map(function (product) {
        if (product.item == item.item) return item;
        else return product;
    });
}

updateBasket({
    item: "Jacket",
    quantity: 9,
    cost: "30"
});
updateBasket({
    item: "Trainers",
    quantity: 9,
    cost: "30"
});
console.log(basket)

#2


0  

Don't know if for you having an array of objects is mandatory if that's not the case you can structure your data differently, for instance

例如,如果不是这种情况,您不知道是否必须以不同的方式构建数据

basket = { items : { item_1 : { quantity: 1, cost: 1 } } }

so updating the basket it will be simply

所以更新篮子就是这么简单

function updateBasket(item, value) {
  // item -> item_1
  // value - > { quantity: 2, cost: 2}
  basket['items'][item] = value;
}

#3


0  

To be honest, I think the problem could be solved if you kept your data in a little different way. For example, something like this

说实话,我认为如果你以一种不同的方式保存数据,问题就可以解决了。例如,像这样的东西

var products  = {
    trousers:0,
    jackets:0,
    trainers:0,
};

var prices = {
    trainers:5,
    jackets: 30,
    trousers: 10
}


//to increase the amount of products after user event
products.jackets  +=2;
products.trainers +=3;
products.trousers +=1;

//finally generate your desired format
var basket = {items:[]};

for(product in products){
   basket.items.push({
       item: product,
       quantity: products[product],
       cost: products[product]*prices[product]
   });
}

console.log(basket);

You can see that basket is now in your desired format :)

你可以看到篮子现在是你想要的格式:)

#4


0  

  • Cost should be a number and not string.
  • 成本应该是数字而不是字符串。

  • If you are not keeping a global object for what is the price of 1 item then once you have updated your basket object you will loose the information on price of 1 item and you wouldn't know how much to increase the price.
  • 如果您没有为1件商品的价格保留全局对象,那么一旦您更新了您的购物篮对象,您将丢失1件商品的价格信息,而您不知道要增加多少价格。

Considering same, below would be my recommendation of changes:

考虑到同样的情况,以下是我对变更的建议:

 var basket = {items:[
                        {item:"Trousers", quantity:4, itemCost:40, totalCost:40},
                        {item:"Trainers", quantity:1, itemCost:5, totalCost:5},
                        {item:"Jacket", quantity:3, itemCost:90, totalCost:90},
                    ]}

function updateQuantity(itemName, qIncreaseBy, qDecreaseBy){
    console.log(basket);
    for(var propt in basket.items){
        if(basket.items[propt].item == itemName){
            if(qIncreaseBy != 0){
                basket.items[propt].quantity = (basket.items[propt].quantity + 1);
                basket.items[propt].totalCost = (basket.items[propt].totalCost + basket.items[propt].itemCost);
            } else{
                basket.items[propt].quantity = (basket.items[propt].quantity - 1);
                basket.items[propt].totalCost = (basket.items[propt].totalCost - basket.items[propt].itemCost);
            }
            break;
        }
    }
    console.log(basket);
}

Usage:

updateQuantity("Trainers", 0, 1);  //To add item
updateQuantity("Trainers", 1, 0)  //To remove item

#1


2  

try this:

var basket = {
    items: [

    {
        item: "Trousers",
        quantity: 1,
        cost: "10"
    }, {
        item: "Trainers",
        quantity: 1,
        cost: "5"
    }, {
        item: "Jacket",
        quantity: 1,
        cost: "30"
    }]
};

function updateBasket(item) {
    basket.items = basket.items.map(function (product) {
        if (product.item == item.item) return item;
        else return product;
    });
}

updateBasket({
    item: "Jacket",
    quantity: 9,
    cost: "30"
});
updateBasket({
    item: "Trainers",
    quantity: 9,
    cost: "30"
});
console.log(basket)

#2


0  

Don't know if for you having an array of objects is mandatory if that's not the case you can structure your data differently, for instance

例如,如果不是这种情况,您不知道是否必须以不同的方式构建数据

basket = { items : { item_1 : { quantity: 1, cost: 1 } } }

so updating the basket it will be simply

所以更新篮子就是这么简单

function updateBasket(item, value) {
  // item -> item_1
  // value - > { quantity: 2, cost: 2}
  basket['items'][item] = value;
}

#3


0  

To be honest, I think the problem could be solved if you kept your data in a little different way. For example, something like this

说实话,我认为如果你以一种不同的方式保存数据,问题就可以解决了。例如,像这样的东西

var products  = {
    trousers:0,
    jackets:0,
    trainers:0,
};

var prices = {
    trainers:5,
    jackets: 30,
    trousers: 10
}


//to increase the amount of products after user event
products.jackets  +=2;
products.trainers +=3;
products.trousers +=1;

//finally generate your desired format
var basket = {items:[]};

for(product in products){
   basket.items.push({
       item: product,
       quantity: products[product],
       cost: products[product]*prices[product]
   });
}

console.log(basket);

You can see that basket is now in your desired format :)

你可以看到篮子现在是你想要的格式:)

#4


0  

  • Cost should be a number and not string.
  • 成本应该是数字而不是字符串。

  • If you are not keeping a global object for what is the price of 1 item then once you have updated your basket object you will loose the information on price of 1 item and you wouldn't know how much to increase the price.
  • 如果您没有为1件商品的价格保留全局对象,那么一旦您更新了您的购物篮对象,您将丢失1件商品的价格信息,而您不知道要增加多少价格。

Considering same, below would be my recommendation of changes:

考虑到同样的情况,以下是我对变更的建议:

 var basket = {items:[
                        {item:"Trousers", quantity:4, itemCost:40, totalCost:40},
                        {item:"Trainers", quantity:1, itemCost:5, totalCost:5},
                        {item:"Jacket", quantity:3, itemCost:90, totalCost:90},
                    ]}

function updateQuantity(itemName, qIncreaseBy, qDecreaseBy){
    console.log(basket);
    for(var propt in basket.items){
        if(basket.items[propt].item == itemName){
            if(qIncreaseBy != 0){
                basket.items[propt].quantity = (basket.items[propt].quantity + 1);
                basket.items[propt].totalCost = (basket.items[propt].totalCost + basket.items[propt].itemCost);
            } else{
                basket.items[propt].quantity = (basket.items[propt].quantity - 1);
                basket.items[propt].totalCost = (basket.items[propt].totalCost - basket.items[propt].itemCost);
            }
            break;
        }
    }
    console.log(basket);
}

Usage:

updateQuantity("Trainers", 0, 1);  //To add item
updateQuantity("Trainers", 1, 0)  //To remove item