Push Array Object Into Localstorage
var arr = []; var obj = {}; obj.order_id = 1; obj.name = 'Cake'; obj.price = '1 Dollar'; obj.qty = 1; arr.push(obj); localStorage.setItem('buy',JSON.stringify(arr)); The proble
Solution 1:
New Answer:
var arr = [];
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
$change = 'no'; for(i=0; i<arr.length; i++){ if(obj.order_id == arr[i].order_id){ obj.qty = obj.qty + arr[i].qty; arr[i] = obj; $change ='yes'; } }
if($change == 'no'){ arr.push(obj); }
console.log(arr);
And for saving it in localstorage see my answer here: push multiple array object into localhost?
Old Answer: The best solution would be to make 'arr' an object with the order_id being the key of the object. You get something like this:
var arr = {};
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
arr[obj.order_id]= obj;
console.log(arr);
This will only replace the order if the order_id is the same. If you really want and array, you have to make a function that goes through the array and checks every order_id.
Post a Comment for "Push Array Object Into Localstorage"