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];
}
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
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.
Mycookies should be an Object, not an Array.
var mycookies = {};
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>
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;
}
Related
suppose i receive JSON object from the server as this
{ "asdf[zxcv]": "qwer" }
how do i access asdf, zxcv, and qwer in javascript, so i can use the object this way ?
theobj.asdf[zxcv] = 'qwer'
Bracket notation is not in the JSON RFC. You can only read it as string.
var simpleObj = {
"simpleKey": "simpleValue"
}
console.log(simpleObj)
var advObj = {
"advKey[1]": "advValue"
}
console.log(JSON.parse(advObj)); // SyntaxError
console.log(advObj.advKey[1]) // TypeError
console.log(advObj["advKey[1]"]) // can only read as string
You would need to refactor the source JSON into something more meaningful so you can access the values in regular JavaScript way.
Run the following snippet to check how you can solve the issue:
var x = '{ "asdf[zxcv]": "qwer" }';
var y = JSON.parse(x);
var result = Object.keys(y).reduce(function(result, key) {
var parentKey = key.substring(0, key.indexOf("["));
var innerKey = /[a-z]+\[([a-z]+)\]/i.exec(key)[1];
if (!result.hasOwnProperty(key))
result[parentKey] = {};
result[parentKey][innerKey] = y[key];
return result;
}, {});
document.getElementById("structure").textContent = JSON.stringify(result);
var zxcv = result["asdf"]["zxcv"];
document.getElementById("someValue").textContent = zxcv;
<h2>Refactored data structure as nested objects:</h2>
<div id="structure"></div>
<h2>Accessing some value: result["asdf"]["zxcv"] or result.asdf.zxcv</h2>
<div id="someValue"></div>
It's all about creating nested objects to represent the associative keys in the source JSON properties representing a conceptual associative array...
This is one of the way to access all elements without reconstructing object.
jQuery.each(JSON.parse('{ "asdf[zxcv]": "qwer" }'), function(index, value) {
var i = index;// i = "asdf[zxcv]"
var v = value;// v = "qwer"
var iOfInnerValue = (/\[(.*?)\]/g).exec(i)[1];// innerValue = "zxcv"
var iOfOuterValue = index.replace("["+(/\[(.*?)\]/g).exec(i)[1]+"]",""); // outerValue = "asdf"
});
You'll need to assign the data to a variable and then you can use Object keys to get the key which is the part before the :. Here's an example.
var j = { "asdf[zxcv]": "qwer" };
console.log(Object.keys(j)); //["asdf[zxcv]"]
console.log(j); //{asdf[zxcv]: "qwer"}
I'm trying to look at all the cookies in a given document with this:
function get_cookies_array() {
var cookies = {};
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}
return cookies;
}
var cookies = get_cookies_array();
alert(cookies.toString());
However, what i'm seeing in the alert box is
[object Object]
I was expecting a comma separated list of values. What am I doing wrong?
The value being returned is not an array. It's a plain object. Presumably you do want to use an object here, so that you can use string-valued keys. You can print out its contents like so:
var cookies = get_cookies_array();
console.log(JSON.stringify(cookies));
Or line by line:
Object.keys(cookies).forEach(function (key) {
console.log(key, ' - ', cookies[key]);
});
Replace var cookies = {}; with var cookies = []; so that you are dealing with an Array instead of an Object.
Then, because you are using an associative array, also change your writing into array like this:
cookies.push([decodeURIComponent(name_value[0]), decodeURIComponent(name_value[1])]);
I need implement this in one line, if possible:
I have an object
var object1 = {};
object1['key_1'] = "value_1";
object1['key_2'] = "value_2";
object1['key_3'] = "value_3";
I need pass to an function one item from object (not only value ), key - only string value
for (var key in object1)
FunctionTemp({key:object1[key]}); // - this don't work as I need, and eval() method I don't want
maybe there is something like this
FunctionTemp((new {})[key]=object1[key]) - its don't work!!! :)
Since you really want it in one line you can do it like this:
var temp;
for (var key in object1)
FunctionTemp(((temp = {}) && (temp[key] = object1[key]))? temp: null);
but I think it is no longer readable as it is, the most ideal solution would be to break it down into several lines.
var temp;
for (var key in object1) {
temp = {};
temp[key] = object1[key];
FunctionTemp(temp);
}
What you're asking for is not possible without a function.
What you want to do is this:
var key = getKey(); //some means of determining a key dynamically
var val = getVal(); //some means of determining a value dynamically
var obj = {};
obj[key] = val;
this.doSomething(obj);
What you need is another method that assembles the object based on the dynamic key/value.
this.doSomething(_.object([[getKey(), getVal()]]));
I'm taking charge of a javascript webapp. It's very complex, and I'm having some trouble with syntax:
getThemeBaseUrl = function() {
var customConfigPath = "./customer-configuration";
if (parseQueryString().CustomConfigPath) {
customConfigPath = parseQueryString().CustomConfigPath;
}
var clientId = parseQueryString().ClientId;
return customConfigPath + "/themes/" + clientId;
};
parseQueryString = function() {
var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
while ( m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
};
in particular parseQueryString().CustomConfigPath and the var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
The first seems to be a sort of property access by the parseQueryString function.
The second seems an array declaration, but without the Array() constructor. Also, the m value is recalled without the presumed array result in the while cycle.
By looking at:
parseQueryString().CustomConfigPath
you can say that parseQueryString() is expected to return an object with CustomConfigPath property.
And from this:
var result = {};
you see that result is indeed an object ({} is an empty object literal). It is not an array. Later, in a loop, there is:
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
so we're assigning properties to the result object. One of this properties will be (as we can expect) a CustomConfigPath. This will be taken from the query string - we'll use regular expression to do this: re = /([^&=]+)=([^&]*)/g. So address of the webpage on which this code is executed looks like: http://example.com/something?SomeKey=value&CustomConfigPath=something.
General syntax for assigning properties to an object is:
result[key] = value;
// key -> decodeURIComponent(m[1])
// value -> decodeURIComponent(m[2])
parseQueryString().CustomConfigPath calls the parseQueryString function, which returns an object. Then it accesses the CustomConfigPath property of that object. A common idiom for the first 4 lines of the function is:
var customConfigPath = parseQueryString().CustomConfigPath || "/.customer-configuration";
var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m is a declaration of 4 different variables, not an array:
result is an empty object
queryString is the query string from the current URL, with the ? removed.
re is a regular expression
m is a variable that isn't initialized, it will be assigned later in the while loop.
I have the following object:
var stuff = {};
stuff["jar"] = "biscuit";
stuff["cupboard"] = "food";
Iterating through the list with an For i loop and getting the value is easy, but how would I get the key?
for (var i in stuff) {
var key = GET KEY SOMEHOW
var val = stuff[i];
}
The key is i. However, make sure that the key is in your object, not part of the prototype chain.
for (var i in stuff) {
var key = i;
if (stuff.hasOwnProperty(i)) {
var val = stuff[i];
}
}
See also:
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
var key = i;
In Javascript's for (foo in bar) if foo is the index of an object or array and happens to be a string, it should print or assign the string when called.
You already have it:
for (var key in stuff) {
var val = stuff[key];
}
If you have the value already you may find the key by using this logic :
for (var i=0;i<numKeyValuePairs;i++)
{
if(val==key[i])
{
document.write(key[i];
}
}