jquery - remove and replace item from object in array javascript -


i have read , tried of posts of on subject, reason none of answers providing desired effect.

i have written shopping basket program , once user clicks the'buy now' button wish make post request containing object users order.

problem

the user has option purchase 3 different items. each time user clicks on item, html input box, increase amount wish purchase want update object contain latest amount chosen.

in simplest format basket, when initiated, looks :

 var basket = {items:[                     {item:"trousers", quantity:1, cost:"10"},                     {item:"trainers", quantity:1, cost:"5"},                     {item:"jacket", quantity:1, cost:"30"}                 ]} 

each time user clicks input button wish basket updated if user clicked increase jacket quantity of 3, , trousers 4 want object this:

 var basket = {items:[                         {item:"trousers", quantity:4, cost:"40"},                         {item:"trainers", quantity:1, cost:"5"},                         {item:"jacket", quantity:3, cost:"90"}                     ]} 

then if user decides reduce number of trousers 1, 3, want basket.items object this:

 var basket = {items:[                             {item:"trousers", quantity:3, cost:"30"},                             {item:"trainers", quantity:1, cost:"5"},                             {item:"jacket", quantity:3, cost:"90"}                         ]} 

i have written code calculations etc. not issue issue update basket.items contain 3 items listed above @ once, latest data.

i cannot use filter method needs work in older versions of ie. have tried solutions listed in this , this along many more none of these answers providing solution looking for.

let me know if further information required.

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) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -