Can I refer to a variable using a string? - javascript

Say I have the following JS:
var foo_index = 123;
var bar_index = 456;
And the following HTML:
<div id="foo"></div>
<div id="bar"></div>
Then I'd like to say this:
thisIndex = this.id + '_index'
And I'd like thisIndex to be a number. How do I turn the string, which is exactly the variable name, into a variable?

You should put the variables in an object, like this:
var indices = {
foo: 123,
bar: 456
};
var thisIndex = indices[this.id];
This code uses JSON syntax an object literal to define an object with two properties and uses [] to access a property by name.
You can also write
var indices = new Object;
indices.foo = 123;
indices["bar"] = 456;

You can. If foo_index and bar_index are global variables, you can simply do:
var thisIndex = window[this.id + '_index'];

you can try using the eval function:
http://www.w3schools.com/jsref/jsref_eval.asp
it does exactly what you need.

window["myvar"] = 'hello';
alert(myvar);

To answer your question, you can use the eval function to evaluate a string:
thisIndex = eval(this.id + '_index');
However, using the eval function is generally a sign of badly constructed code. I think that you should use an associative array instead:
var numbers = { foo: 123, bar: 456 };
thisIndex = numbers[this.id];

I am not sure what do you want to achieve, but maybe this approach could be better (it depends on some factors like version of HTML you use as #Andy E points in comment below):
<div id="foo" index="123"></div>
<div id="bar" index="456"></div>
<script>
var fooIndex = document.getElementById("foo").getAttribute("index");
</script>
Here value of index is kept together with corresponding HTML element.

I think you want something like this:
// put your properties in an object of some kind
var dictionary =
{
foo_index: 123,
bar_index: 456
};
// you can set further properties with property syntax
dictionary.again_index = 789;
// or dictionary syntax - same result
dictionary['another_index'] = 012;
// then function to get the number value from the index name becomes
var thisIndex = Number(dictionary[this.id + '_index']);

Related

Using variables to build JS Object

I want to create an object that has some keys which come from a variable parameter.
Let's say for example that prod_id below is a variable containing some value... I want to create an object which has an attribute with key of that 'prod_id' and value of 1. However this does not work? Is this possible to achieve? if so, how? thanks a heaps
var cart_obj;
cart_obj = {
prod_id : 1
};
localStorage.setItem("cart", JSON.stringify(cart_obj));
You can't do it with a simple object literal. You can do this however:
var cart_obj = {};
cart_obj[prod_id] = 1;
JavaScript object literal syntax makes no provisions for expressions on the left side of a property declaration stanza.
var cart_obj = {};
cart_obj.prod_id = 1;
or
var cart_obj = {};
cart_obj[prod_id] = 1;

How to call object and its method with a variable

I have a bunch of jQuery objects with a init method, so right now I have something like this
$.myobject1.init(somevar);
$.myobject2.init(somevar);
$.myobject3.init(somevar);
$.myobject4.init(somevar);
$.myobject5.init(somevar); // somevar is the same var in all the calls
but I'm looking for a way to simply this code, something like this
var objectName = "myobject1"; // or any other object name
$. objectName .init(somevar);
thanks for the help! :-)
Since they are already jQuery objects you don't need $. and you can use .add() like this :
var object = myobject1.add(myobject2).add(myobject3).add(myobject4).add(myobject5);
object.init(somvar)
Just use
$[objectName].init(somevar);
in javascript, all objects are maps. it's really weird, but it means you can do this trick:
var p = "mypropertyname";
var obj = {};
obj[p] = somevalue;
then, if you do:
console.log(obj.mypropertyname)
you'll get:
> somevalue
If you mean you want to loop through the names of your objects, then you should know that you can't combine strings with dot notation:
var someObj = {
subObj: {
a: 5
}
};
someObj.subObj.a === 5; // true
someObj."subObj".a === 5; // throws error
But you can use strings with square bracket notation:
someObj["subObj"].a === 5; // true
var propName = "subObj";
someObj[propName].a === 5; // true
So you can use that to loop through your object names with a for loop, or you can use a jQuery method as suggested in other answers.

How to set a Javascript object values dynamically?

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

How can I store reference to a variable within an array?

I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.
var name = "foo";
var array = [];
array["reference"] = name;
name = "bar";
// Still returns "foo" when I'd like it to return "bar."
array["reference"];
Is there a way to make the array refer to the variable?
Put an object into the array instead:
var name = {};
name.title = "foo";
var array = [];
array["reference"] = name;
name.title = "bar";
// now returns "bar"
array["reference"].title;
You can't.
JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.
If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".
Btw, [] is an array literal. {} is an object literal.
That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.
And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).
Try pushing an object to the array instead and altering values within it.
var ar = [];
var obj = {value: 10};
ar[ar.length] = obj;
obj.value = 12;
alert(ar[0].value);
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called myTarget, then use:
myRef = function (newVal) {
if (newVal != undefined) myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(<the value you want to set>);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray[0]() to read and myArray[0](<new value>) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called 'myTarget', then use:
myRef = function (newVal) {
if (newVal != undefined)
myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(value_to_set);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray0 to read and myArray[0](value_to_set) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.

Determine original name of variable after its passed to a function

I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";
This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.
You're right, this is very much impossible in any sane way, since only the value gets passed into the function.
This is now somehow possible thanks to ES6:
function getVariableName(unknownVariableInAHash){
return Object.keys(unknownVariableInAHash)[0]
}
const foo = 42
const bar = 'baz'
console.log(getVariableName({foo})) //returns string "foo"
console.log(getVariableName({bar})) //returns string "bar"
The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.
As you want debugging (show name of var and value of var),
I've been looking for it too, and just want to share my finding.
It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.
It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :
foo = 'bar';
debug('foo');
function debug(Variable) {
var Value = this[Variable]; // in that occurrence, it is equivalent to
// this['foo'] which is the syntax to call the global variable foo
console.log(Variable + " is " + Value); // print "foo is bar"
}
Well, all the global variables are properties of global object (this or window), aren't they?
So when I wanted to find out the name of my variables, I made following function:
var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = "Hello World!";
console.log(getName(helloWorld)); // "helloWorld"
Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.
Global w/string method
Here is a technique that you can use to keep the name and the value of the variable.
// Set up a global variable called g
var g = {};
// All other variables should be defined as properties of this global object
g.foo = 'hello';
g.bar = 'world';
// Setup function
function doStuff(str) {
if (str in g) {
var name = str;
var value = g[str];
// Do stuff with the variable name and the variable value here
// For this example, simply print to console
console.log(name, value);
} else {
console.error('Oh snap! That variable does not exist!');
}
}
// Call the function
doStuff('foo'); // log: foo hello
doStuff('bar'); // log: bar world
doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!
This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.
ES6 object method
In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.
function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}
var foo = 'hello';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);
This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.
Credit goes to this tweet.
Converting a set of unique variable into one JSON object for which I wrote this function
function makeJSON(){ //Pass the variable names as string parameters [not by reference]
ret={};
for(i=0; i<arguments.length; i++){
eval("ret."+arguments[i]+"="+arguments[i]);
}
return ret;
}
Example:
a=b=c=3;
console.log(makeJSON('a','b','c'));
Perhaps this is the reason for this query
I think you can use
getVariableName({foo});
Use a 2D reference array with .filter()
Note: I now feel that #Offermo's answer above is the best one to use. Leaving up my answer for reference, though I mostly wouldn't recommend using it.
Here is what I came up with independently, which requires explicit declaration of variable names and only works with unique values. (But will work if those two conditions are met.)
// Initialize some variables
let var1 = "stick"
let var2 = "goo"
let var3 = "hello"
let var4 = "asdf"
// Create a 2D array of variable names
const varNames = [
[var1, "var1"],
[var2, "var2"],
[var3, "var3"]
]
// Return either name of variable or `undefined` if no match
const getName = v => varNames.filter(name => name[0] === v).length
? varNames.filter(name => name[0] === v)[0][1]
: undefined
// Use `getName` with OP's original function
function getVariableName(unknownVariable){
return getName(unknownVariable)
}
This is my take for logging the name of an input and its value at the same time:
function logVariableAndName(unknownVariable) {
const variableName = Object.keys(unknownVariable)[0];
const value = unknownVariable[variableName];
console.log(variableName);
console.log(value);
}
Then you can use it like logVariableAndName({ someVariable })

Categories