Setting array key value pair JavaScript

1.5k views Asked by At

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];
}
5

There are 5 answers

1
Drakes On BEST ANSWER

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

0
Andy Gaskell On

mycookies should be populated assuming temp.length is greater than 0. Your return value is always going to be undefined; mycookies[cookiename] is never assigned a value.

Try adding console.log(mycookies) just before your return statement.

0
clickbait On

Mycookies should be an Object, not an Array.

var mycookies = {};
3
jherax On

My friend, you are a little confused (maybe you have programmed in PHP) because in JavaScript, an Array is not a associative key : value object, it is an indexes based object. But what you looking for is an Object Literal

function getcookie (cookiename){
    var i, max, keyvalue, key, val,
        cookiesObj = {}, //empty object literal
        cookiesArr = document.cookie.split(";");
    for(i=0, max=cookiesArr.length; i<max; i+=1) {
        keyvalue = cookiesArr[i].split("=");
        key = keyvalue[0].trim();
        val = keyvalue[1].trim();
        cookiesObj[key] = val;
    }
    return cookiesObj[cookiename];
}

But you can refactor your code:

function getcookie (cookiename) {
    var cookie = "",
        cookies = document.cookie.split(";");
    cookies.forEach(function (item) {
        var keyvalue = item.split("="),
            key = keyvalue[0].trim(),
            val = keyvalue[1].trim();
        if (key === cookiename) {
            cookie = val;
            return false; //exit from iteration
        }
    });
    return cookie;
}
0
Marko Gresak On

JavaScript arrays are not associative arrays, only possible index values are numerical, starting with 0 and ending at array.length - 1. What you might have seen in examples before or used in another language before was JavaScript object, which does, in fact, behave as an associative array. You can access object values by object['key'] or as object.key. The first is used only when accessing key using a variable or a key which includes illegal characters, i.e. some-key, otherwise it's recommended to use dot access, as illustrated in second example.

Therefore your mycookies variable should be an object, not an array.

If you change your line var mycookies = []; to var mycookies = {};, i.e. change it from empty array to empty object, the remaining code should work as you expected.

Here is an example snippet for fixed code, I added a mock cookies string so it can work reliably:

var mockCookies = "a=1;b=2;c=3";
function getcookie(cookiename){
     var mycookies = {}; // The cookie jar 
     var temp = mockCookies.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];
}


function printCookie(name) {
    alert(getcookie(name));
}
<button onclick="printCookie('a')">Get a</button>
<button onclick="printCookie('b')">Get b</button>
<button onclick="printCookie('c')">Get c</button>