简体   繁体   中英

Create or Update cookie array in Jquery

I want to create if the value is 0 and update if the value is 1.

So I wrote this one,

var juiceCart = [{
    'name': val,
    'count': unTouch
}];
if (value == 0) {
    console.log('create cookie');
    $.cookie("juiceCart", JSON.stringify(juiceCart));
    doDummyCall();
} else {
    console.log('update cookie');
    $.cookie("juiceCart", JSON.stringify(juiceCart));
    doDummyCall();
}

Inside the doDummyCall()

I am just doing a ajax call to update the headers and

var cookieJuiceCart = $.parseJSON($.cookie("juiceCart"));
$.each(cookieJuiceCart, function (index, value) {
    console.log('Id : ' + value.name);
    console.log('Value : ' + value.count);
});

and then printing the cookie in each function to know all the items present in it.

If i add the first item, it is printing

Id : 1 Value : 1

Then, if i add the Second item it is printing

Id : 2 Value : 1

But what i expect is

Id : 1 Value : 1 Id : 2 Value : 1

I know that the old value is replaced because i am not pushing the value in it.

So, I did

juiceCart.push({'name': val, 'count': unTouch});

But it is just replacing the old value with new one.

How can i check the existence of old value inside the array and create or update according to it.

The actual problem seems to me is your array:

var juiceCart = [{
    'name': val,
    'count': unTouch
}];

which is using vars to update same object instead of pushing new object.

You can do this:

var juiceCart = $.parseJSON($.cookie("juiceCart")) || []; // create a blank array taken from @apokryfos's answer.
juiceCart.push({'name': val, 'count': unTouch}); // <---now push it here.

This way you are able to push new object each time you call it.

This is what I got from the question. It's a bit poorly explained so I may not have understood what you need to do.

var juiceCart = $.parseJSON($.cookie("juiceCart")) || [];
var newItem = true;
juiceCart.each(function (i, v) { 
    if (v.name == val) { v.count++; newItem = false; }
});
if (newItem) {
    juiceCart.push({'name': val, 'count': unTouch});
}
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM