Javascript / Jquery - How to set a variable name based on a variable - javascript

This has been asked a bunch of times before but I'm not grasping it.
In the following..
var variableName = "hello";
How do I make the variable name 'variableName' based on another variable?
PHP Example
$a = 'hello';
$$a = 'hi'; // same as $hello..
echo $hello; // and $hello outputs 'hi'
I specifically need this variable variable to be used for localstorage so it may be syntax that I'm having a problem with.
What I'm Using It For (you can probbaly skip to This Seems To Work)
I want to generate a unique variable name for storing information in local storage. Variable name will be based on the post id of the wordpress post/page which I retrieve with php.
For example we will say the post id is 3333
I add the letters id to the beginning of each post id
So now I have id3333
var postIdNumber = 'id3333';
Then I get 3 other pieces of information that I want to store into local storage about this post (for simplicity I have shown an example output, not the code to get it)
var postURL = 'website.comm/a-wp-post/';
var postTitle = 'A Wordpress Post';
var postThumb = 'website.comm/images/thumb3333.jpg';
Now I want to store this information into local storage
var lsTest = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('lsTest', JSON.stringify(lsTest));
That works fine. Except that I want to be able to store multiple posts into local storage to retrieve later from a 'my favourite posts' page.
So I need a dynamic variable name.
For post ID 3333 I need the variable currently named lsTest to be named id3333
For post ID 4444 I need the variable currently named lsTest to be named id4444
This seems to work (Though I dont fully comprehend it)
solution modified from https://stackoverflow.com/a/5187652/3377049
var variableVariable = {}
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
jQuery('.test-div').text(variableVariable[vv]); // outputs id3333
While this does not..
var variableVariable = {} // also, should this have a ';' ?
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
var variableVariable[vv] = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('variableVariable[vv]', JSON.stringify(variableVariable[vv]));
In PHP I could maybe do something like this.. (for examples sake i'm mixing php variables into JS)
$uv = 'id3333';
$$uv = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('$$uv', JSON.stringify($$uv));

You just need to create an object of objects, keyed off of the unique post id. But then you need to stringify the object before storing it, and parse it when retrieving it.
function saveObject(key, object) {
object = JSON.stringify(object);
window.localStorage.setItem(key, object);
}
function getSavedObject(key) {
var saved = window.localStorage.getItem(key);
if (saved) {
return JSON.parse(saved);
} else {
return null;
}
}
your object:
var lsTest = {
id3333: {
postUrl: postUrl1,
postTitle: postTitle1,
postThumb: postThumb1,
},
id4444: {
postUrl: postUrl2,
postTitle: postTitle2,
postThumb: postThumb2,
}
}
store it:
saveObject('myUniqueSiteName', lsTest);
retrieve it:
var lsTest = getSavedObject('myUniqueSiteName');
adding a new post:
var lsTest = getSavedObject('myUniqueSiteName');
var postId = 'id555';
lsTest[postId] = {
postUrl: postUrl3,
postTitle: postTitle3,
postThumb: postThumb3,
}
saveObject('myUniqueSiteName', lsTest);

Variable variables are not a good idea even in PHP. Just make an array or a hash (which is an object, but it's used as a hash or map, where you can add and delete properties or entries as you please).
var posts = {};
var someId = 3333; //or '3333' if it isn't a number
posts[someId] = {
URL: postURL,
title: postTitle,
thumb: postThumb
};
localStorage.setItem('post' + someId, JSON.stringify(posts[someId]));
A property named "foo" on an object named "bar" can be accessed like so:
bar.foo = 'baz';
console.log(bar.foo);
or like so:
bar['foo'] = 'baz';
console.log(bar['foo']);
Which is the same as:
var name = 'foo';
bar[name] = 'baz';
console.log(bar[name]);
Finally, the global object in JavaScript (which in the browser is window) "holds" the global variables.
var myGlobal = 10;
console.log(window.myGlobal); // logs 10
var globalName = 'foo';
window[globalName] = 'baz';
console.log(foo); //logs 'baz'
Using global variables in general is discouraged. Using them to store posts where the name of the var is the id is highly unorthodox and many JS developers would consider it simply wrong.

Related

How to assign (add) value to a undefined item in a json object

I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:
//I parse my JSON into object and name it data
var data = {
...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
// ...
// "title": "hello guys",
// ...
//}
But the vscode's console show the following error when I run the script
TypeError: Cannot set property 'title' of undefined
If you can assign value to undefined object how can you add item in to object.
But if there is any way that can let me assign value to undefined item, I'll be very happy
Here is the full code if you need
var jsonfile = require('jsonfile')
var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;
jsonfile.writeFileSync(file, tmd, {spaces: 4});
currently data = undefined and you are trying to access a key in undefined that is why you are getting an error, you need to assign an empty object to data if it is undefined. you can do something like this:
var data = data || {};
var name = "title";
var content = "hello guys";
data[name] = content;
Probably data has no key named 'post'.
Try this:
data.post = data.post || {};
data.post[name] = content;
EDIT:
I know this is old, but maybe it will help someone.
Here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options states that readFileSync returns string not data structure.

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

capturing a specific value from a cookie javascript

I have a cookie set up which has data stored in the following format:
{"g":"776","f":"88876","hit":"true","TESTVALUE":"this is the value i want to capture"}
I want to capture "TESTVALUE" in its own variable.
I am using this script to actually capture the cookie data (where the cookie is called "chocolateChip":
var getCookie = function (name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
} // code indentation
var cookie = getCookie(chocolateChip);
Im then using the following script to pass the "testvalue" string to its own variable:
var test = cookie.TESTVALUE;
However this does not seem to work.
The cookie value is a JSON string, which you need to parse to get an actual JS object.
Try this:
var cookie = getCookie(chocolateChip);
var test = JSON.parse(cookie).TESTVALUE;
Or, if you need to access more properties:
var cookie = getCookie(chocolateChip);
var cookieObject = JSON.parse(cookie);
var testValue = cookieObject.TESTVALUE;

Use non-static variable with chrome.storage.local.set / get

Is it possible to use a non static variable with chrome.storage.local.get. Right now, I can not recover anything.
here's what I do:
myVar = 'test';
var obj = {};
obj[myVar] = Output;
storage.set(obj);
and to recover, I do:
var key = example + 'js';
storage.get(key, function (result) {
console.log (result.key)
});
Thank you in advance for your help!
You can pass null as the query to retrieve the whole storage:
chrome.storage.local.get(null, function(data) {
// data contains everything in storage
});

JSON stringify and then parse works unexpectedly for the object with local variable

Why JSON stringify and then parse is not working for this object. Is it works bad for objects with local variables?
function Task(description) {
var _description = description;
this.getDescription = function() {
return _description;
}
}
var task = new Task('wash car');
console.log(task.getDescription());
var json = JSON.stringify(task);
console.log(JSON.parse(json).getDescription());
JSON can't stringify functions (and it's not supposed to be able to).
But technically when you need to Stringify an object you should not need the functions. You can just pass the object as is within your application.
EDIT:
If what you need is the object to be stored locally then saving the functions along with it would not be a good idea anyway. What you can do is store the properties of the object and create a new instance when you retrieve it.
It isn't possible to stringify an instance of a constructor and for it to still be an instance of the constructor after turning it back into an object.
Instead, you would need to give the Task instance a method that outputs a json string that you can store, then when you want it to be an instance of Task again, you can create a new instance.
function Task(description) {
var _description = description;
this.getDescription = function() {
return _description + '(possibly modified?)';
}
this.stringify = function () {
return JSON.stringify({
description: this.getDescription(),
_description: _description
});
}
}
var task = new Task('wash car');
console.log(task.getDescription()); // 'wash car (possibly modified?)'
var json = task.stringify();
console.log(json); // {"description": "wash car (possibly modified?)", "_description": "wash car"}
var taskAgain = new Task(JSON.parse(json)._description);
console.log(taskAgain.getDescription()); // 'wash car (possibly modified?)'
I added the " (possibly modified?)" to demonstrate why it is important to pass both the result of getDescription and the string stored in _description. if getDescription never changes the description, there is no need to have getDescription in the first place which greatly simplifies this whole process.
function Task(description) {
this.description = description;
}
var task = new Task('wash car');
console.log(task.description); // wash car
var json = JSON.stringify(task);
console.log(json); // {"description": "wash car"}
console.log(JSON.parse(json).description); // wash car
var taskAgain = new Task(JSON.parse(json).description);
console.log(task.description); // wash car

Categories

Resources