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 problem with above code is when executing it will replace the existing array object, how to add new obj into the array if the order_id is not the same?
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.