0

Hi I have cookie which has value of serialized params.

i.e)criteria = "name=praveen&age=25&studying=false&working=true&something=value"

Now I have to update name = praveenkumar,age = 24,something = null in this cookie string. If value is null(something = null) then it should be removed from cookie. The following is the code I am using.

updateCookie({'name':'praveenkumar','age':24,'something':null})
var updateCookie = function(params) {
// split the cookie into array
var arr = $.cookie('criteria').split("&");
//loop through each element
for(var i = arr.length - 1; i >= 0; i--) {
  // getting the key i.e) name,age
  var key = arr[i].split("=")[0];
  // if the key is in given param updating the value
  if( key in params) {
    // if vale null remove the element from array or update the value
    if(params[key] !== null) {
      arr[i] = key+"="+params[key];
    }
    else {
      arr.splice(i, 1);
    }
  }
}
// join array by & to frame cookie string again
$.cookie('criteria' , arr.join("&"));

};

It is working. But I am concerned about performance if the size of cookie become more.

Praveenkumar
  • 921
  • 1
  • 9
  • 28

1 Answers1

0

Way too complicated. Try this instead :

var criteria = "name=praveen&age=25&studying=false&working=true&something=value";

Turn the serialized string into a object

var obj = JSON.parse('{"' + decodeURI(criteria)
                           .replace(/"/g, '\\"')
                           .replace(/&/g, '","')
                           .replace(/=/g,'":"') 
                  + '"}')

Based on this answer. Now you can manipulate the object

obj.studying = null;

Remove null values from the object

for (prop in obj) {
  if (obj[prop] == null) delete obj[prop]
}

use jQuery's $.param to get the modified object as serialized string

criteria = $.param(obj);

== name=praveen&age=25&working=true&something=value

save the updated cookie value

$.cookie('criteria', criteria);

I do not understand the concern about performance, You should never expect a browser to allow more than 4096 bytes in a cookie. If performance and size is a concern you should use localStorage. It is much faster than cookies and has capacity measured in MB's (vary from browser to browser).

Community
  • 1
  • 1
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • @davidkonard It was really helpfull. The performance thing is number of parameter stored in cookie may increase, enumerating through each param may cost more. – Praveenkumar Dec 05 '16 at 06:17