I am reading cookie value for Cookie Consent "CookieScriptConsent" which can store values in different ways such as
{"action":"reject","categories":"[]"}
{"action":"accept","categories":"[]"}
{"action":"accept"}
{"action":"accept","categories":"[\"performance\",\"targeting\",\"functionality\"]","key":"58abddd4-493e-499a-9711-67644adc39af"}
{"action":"accept","categories":"[\"performance\"]","key":"24b56441-d831-4cd1-8e5f-47353257f500"}
I am using a cookie reading plugin which reads cookie value Cookies.get('CookieScriptConsent');
I store this value in variable and now i need to read values if cookie was accepted or rejected.
var string= Cookies.get('CookieScriptConsent');
var res = str.match(/accept/gi)
i am using match function of js to see if i find a match, it will return value or null how can i use this if if statement or what is the best way to achieve this
should i use var n = str.indexOf("accept"); as it will give me numeric value which can easily be used in if statement to check if value is greater than 0
If the data stored in the cookie is a JSON object stringified, you can try to parse it and check if the property matches with the value you are looking for:
function getCookieData() {
var cookie = Cookies.get("CookieScriptConsent");
console.log("Raw data: ", cookie);
if (cookie) {
var scriptConsent = JSON.parse(cookie);
if (scriptConsent.action === "accept") {
console.log("Consented!");
} else {
console.log("Rejected!");
}
} else {
console.log("Cookie do not exists");
}
}
This also allows you to check if this particular property has the value.
Hope it helps!
Related
I have a settings.json file that contains following data (where 123456789 is a distinct user id):
{
"123456789":
{"button_mode":true}
}
So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all.
Here's a snippet of it (Node.js):
var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))
Does anybody have ideas on how it can be implemented? Any help appreciated.
You can use bracket notation to add a dynamic property to an object:
lcSettings[id] = { button_mode: false };
You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.
To 'push' elements to an object you simply define them, as in
object['123456789'] = { button_mode: true };
I have created this JS object from an array.
var rv = {};
$( ".part-name:visible" ).each(function( index ) {
//rv[$(this).text()] = arrayPartsName[$(this).text()];
rv[$(this).text()] = arrayPartsName[$(this).text()];
console.log(rv);
})
4GN: "4GN"
4GNTS: "4GNTS"
042645-00: "042645-00"
503711-03: "503711-03"
573699-05: "573699-05"
I have to use this object with Materialize Autocomplete and I have to edit it. The correct object must be, for example, like this
4GN: null
4GNTS: null
042645-00: null
503711-03: null
573699-05: null
How can do this?
Picking up from my comment. You can just set it to null ;) JavaScript is quite a cool language... you can pretty much set any object's properties to anything you want, null, a specific value, or even a function... see some more on the topic
But to focus on your specific question:
Change this line
rv[$(this).text()] = arrayPartsName[$(this).text()];
to
rv[$(this).text()] = null;
Something to be aware of
If you have property or key values in the JSON object with a dash in the name, you have to wrap it in quotes ", otherwise it wont be seen as valid. Although this might not be as evident, or an issue in your example as your keys are being added via the following function $(this).text().
var fruit = {
"pear": null, // something null
"talk": function() { console.log('WOOHOO!'); } // function
}
var apple = "app-le";
fruit[apple.toString()] = 'with a dash';
fruit["bana-na"] = 'with a dash';
// below is not allowed, the values will be evaluated as
// properties that dont exist, and then your js will fail
// fruit[pe-ar] = 'with a dash';
fruit.talk();
console.log(fruit);
How to get the Object from a string?
I written a localStorage util, in it there are get and set methods.
in the set method:
function fnGet(name){
var getVal=storage.getItem(name);
if(getVal==null){
return console.log('the localstorage did\'t have'+name);
}
if((getVal.split(':-:')).lenght>1){
return eval('('+getVal.split(':-:')[0]+')');
}
return getVal.split(':-:')[0];
}
You can ignore the :-:, it is the separator of the saved data and timestamp.
there is a problem, if the data is stored a JavaScript Object, such like this:
'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}:-:1521381469910'
when I use the get method, it will become like this:
'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}'
How can I get to the JavaScript Object?
How to optimize my get method?
JSON.parse on your response from the store. localStorage stores everything as strings so you would need to stringify the object at first, as Im supposed you do as otherwise you wouldnt have been able to save it to the store.
Then to retrieve it you would need to parse it to get the javascript object again.
Two things:
Use JSON.parse() instead of eval; it's not only safer, but more descriptive as to what your intent is. Note: this requires using JSON.stringify() on the data being saved in localStorage
Correct your spelling errors; you would never get to the eval/parser block because your length was spelled "lenght"
function fnGet(name) {
let getVal = storage.getItem(name)
if (getVal == null) {
return console.log(`the localstorage did't have: ${name}`);
}
let val = getVal.split(':-:'); // for performance cache the split
if (val.length > 1) { // Spelling error: "lenght" -> length
return JSON.parse(val[0]);
}
return val[0];
}
LocalStorage saves the data stringified. So you should use JSON.parse(yourVariable) to get the data back as JSON
function fnGet(name) {
var getVal = storage.getItem(name);
if (getVal == null) {
return console.log('the localstorage did\'t have' + name);
}
if ((getVal.split(':-:')).lenght > 1) {
return eval('(' + JSON.parse(getVal.split(':-:')[0]) + ')');
}
return getVal.split(':-:')[0];
}
all you needed was JSON.parse which takes a string as an argument and if its a valid object string ,returns an object else throws an error
I want to do something relatively simple, I think anyways.
I need to compare the pathname of page with an object's kv pairs. For example:
if("pathname" === "key"){return value;}
That's pretty much it. I'm not sure how to do it in either regular Javascript or jQuery. Either are acceptable.
You can see my fiddle here: http://jsfiddle.net/lz430/2rhds1x3/
JavaScript:
var pageID = "/electrical-electronic-tape/c/864";
var pageList = [{
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
}];
var label = pageID in pageList;
$('.el').html(label);
First, your "pageList" should just be a plain object, not an object in an array:
var pageList = {
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
};
Then you can set "label" to the value from the mapping:
var label = pageList[pageID] || "(not found)";
That last bit of the statement above will set the label to "(not found)" if the lookup fails, which may or may not be applicable to your situation.
It depends kinda on the logic you want to implement. If you want to say "if object has the key, then do X, and if not, then do Y", then you handle that differently than "set label to the object's key's value if the key is there, or else set it to undefined or something else".
For the first case you do:
if (pageList.hasOwnProperty(pageID) ) {
label = pageList[pageID];
}
else {
// do whatever, maybe some error?
}
For the second case, you can just say
var label = pageList[pageID] || 'notFound';
As indicated by #Pointy, either get rid of the array or subsiture pageList[0] for pageList and pageList[0][pageID] for pageList[pageID] above, if you need to keep the array.
I did this javascript quiz : http://utbm.trunat.fr/CIP/quiz/
It works on normal browser but doesn't even load with Internet Explorer.
It seams that it doesn't recognize the initQuiz() function.
Do you have any idea of how I can fix this ?
Internet Explorer doesn't accept the trailing comma:
question = {'texte': $(this).attr("texte"),
'sound': $(this).attr("sound"),}
Apparently, another error comes from this line:
$('title').html(QUIZ_TITLE[lang]);
Turns out you can't set the title like that in IE. Use document.title = QUIZ_TITLE[lang] instead.
A third error is that you're introducing a new variable, question without the var keyword, which is an error in IE. You're doing it again, later on, in response. Update your loadXML as such:
function loadXML(xml) {
$(xml).find("question").each(function() {
var question = {'texte': $(this).attr("texte"), 'sound': $(this).attr("sound")};
reponses = [];
$(this).find('carre').find('reponse').each(function() {
var reponse = {'texte': $(this).text(), 'sound': $(this).attr("sound"), 'bonne': false};
if($(this).attr('bonne') == "vrai") reponse['bonne'] = true;
reponses.push(reponse);
});
question['reponses'] = reponses;
questions.push(question);
});
startGame(questions);
}
A fourth error is in the way you're verifying that an answer is correct.
if($(this).attr('data-type') == 'true')
You compare the value of the data-type attribute to the string value "true", but when you assign the value, you set it to the boolean value true:
$('#r'+(i+1)+'input').attr('data-type', r.bonne);
To make sure that you're always comparing string values, for instance, you could set the value as such:
$('#r'+(i+1)+'input').attr('data-type', r.bonne.toString());