-1

I am using express.js and the cookie-parser middleware. I am trying to use a function to push the cookie name and the cookie value into an array.

I want the array to end up looking like the following:

loop = [{cookie1: value1}, {cookie2: value2}];

But for some reason when I push the key and the value into the array, the key is just being assigned as a string called key, instead of the actual value set in the function. So my array ends up looking like the following:

loop = [{key: value1}, {key: value2}];

I define the variable 'key' inside the function, and if I console log it inside the function it is set to the right value (i.e cookie1), but for some reason when I try to push it into the array, it just pushes in 'key' instead of the actual variable.

Below is the full function, any ideas would be greatly appreciated. Thanks.

var loop = [];
cookie_objects(req.cookies);

function cookie_objects( cookies ) {
    for (var cookie in cookies) {
        if ( cookie != 'seen_cookie_message' && cookie != '_ga' ) {
            var key = cookie;
            var value = cookies[cookie];

            loop.push({key : value});
        }
    }
}
abbott567
  • 862
  • 6
  • 18
  • 1
    Possible duplicate of [Using a variable for a key in a JavaScript object literal](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – CBroe Dec 08 '15 at 16:19

1 Answers1

2

You have to create the blank object beforehand - then assign the key via bracket notation:

var obj = {};
obj[key] = value;
loop.push(obj);
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Amazing! solved in literally under a minute haha... Thanks so much! As soon as it will let me accept this answer I will do so. – abbott567 Dec 08 '15 at 16:20