Search code examples
javascriptarrayskeyvaluepair

Setting array key value pair JavaScript


So, I am having an issue and for the life of me I cannot seem to resolve it. It seems very basic, but I just cannot understand for the life of me why this code is not working.

My issue is, I am assigning a key value pair to an array, but the values DO NOT get assigned. Is it a variable scope issue?

Here is my code

function getcookie(cookiename){
     var mycookies = []; // The cookie jar 
     var temp = document.cookie.split(";");
     var key  = "";
     var val  = "";
     for(i=0;i<temp.length;i++){
         key = temp[i].split("=")[0];
         val = temp[i].split("=")[1];
         mycookies[key] = val;
     }
     return mycookies[cookiename];
}

Solution

  • Trim your key because cookie strings look like this:

    "__utma=250730393.1032915092.1427933260.1430325220.1430325220.1; __utmc=250730393; __utmz=250730393.1430325220.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); clicks=22; _gat=1; _ga=GA1.2.1032915092.1427933260"

    so when you split on ; there will be an extra space before some of the key names.

    function getcookie(cookiename){
         var mycookies = []; // The cookie jar 
         var temp = document.cookie.split(";");
         var key  = "";
         var val  = "";
         for(i=0;i<temp.length;i++){
             key = temp[i].split("=")[0].trim(); // added trim here
             val = temp[i].split("=")[1];
             mycookies[key] = val;
         }
         return mycookies[cookiename];
    }
    

    Demo: JSBin