javascript - 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 problem above code when executing replace existing array object, how add new obj array if order_id not 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 saving in localstorage see answer here: push multiple array object localhost?

old answer: best solution make 'arr' object order_id being key of object. 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 replace order if order_id same. if want , array, have make function goes through array , checks every order_id.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -