Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...