0

I want to add the object value to cookie array without push array to cookie. how can i do that ?i can use cookieDevObjArray.push(obj); but i want to push my object to cookie not whole array.How can i do that any help? Here is object

 var obj =
 {
    'deviceid': deviceId,
    'full': cookiefull,
    'stacked': istoggle

 };

 $.cookie("cookieDevObjArray", + JSON.stringify(obj), { expires: 30 });

this code only save current object and override previous data.

3
  • Maybe you want to use the spread operator? Commented Mar 21, 2021 at 16:56
  • how can i use that ? Commented Mar 21, 2021 at 16:57
  • When you want to "merge" an object into an existing array as a new element of the array you can do newCookieObjArray = [...cookieObjArray,...obj]. Just use it like this: ...obj The spread operator only takes key:value pairs from an array instead of the whole array/object Commented Mar 21, 2021 at 18:13

1 Answer 1

1

You should first get your specific cookie key then parse it and doing your operation then set the cookie again

 var obj =
 {
    'deviceid': deviceId,
    'full': cookiefull,
    'stacked': istoggle

 };

// First get your previous cookie
const array = JSON.parse($.cookie("cookieDevObjArray"))
array.push(obj)

// Setting new value
$.cookie("cookieDevObjArray", + JSON.stringify(array), { expires: 30 });

Sign up to request clarification or add additional context in comments.

6 Comments

Need to consider case where no JSON array exists in that cookie also
I want to push only object not full array to new cookie. any help
@fazalabbas It is impossible as far as I know
in javasciprt we use document.cookie +=name="value" for adding new cookie add with existing but in jquery how can i do that?
@fazalabbas When you are using += you are overwriting the variable again and does not make a difference with my method
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.