javascript access object with variable name - javascript

I am trying to access an object but the name is variable. So:
I have object41, object42 and object43. I want to access object42.
id = 42;
something like this:
object+id.function();
I have searched and found how to assign objects with variable names and how to access properties with variable names but I can't figure out how to access objects with variable names.
Is this something obvious that I am missing?

If these objects are global, you can access them via the window object, and then call your function on the resulting object.
var id = 42;
window["object" + id].function();

Try using eval
// Sample object
function X(id) {
this.value1 = "A" + id;
this.function = function f(value){
alert(value);
};
return this;
}
// n number of object created
var object1 = new X(1);
var object2 = new X(2);
// iterate over all object
for (i=1; i<=2; i++) {
var expr = "object"+i+".function(object"+i+".value1)";
eval(expr);
}
Here a jsfiddle : demo

Related

Unexpected result pushing objects into an array

How to iterate over an array of literal objects in JavaScript?
I would like to do something like that:
grupo = []; // declare array
text = {}; // declare new object
text.a = "texta"; // declare property "a" of an object.
text.b = "textb";
grupo.push(text); // add object to array
text = {}; // declare new object
text.a = "textc"; // declare property
grupo.push(text); // add object with other property
// Iterate over
for (i=0; i<=grupo.length; i++) {
console.dir(grupo[i].text.a);
}
There are various errors in that code:
You're putting the same object in the array twice, not putting two objects in the array. After you push text into the array, you're just overwriting the a property on the same object and pushing it again. You haven't created a new object.
You haven't declared any of your variables (everywhere you've said "declare" in your comments, those are not declarations), so you're falling prey to The Horror of Implicit Globals. Use var to declare variables.
A line comment should start with //, not \\ (those cause a syntax error)
The for loop at the end should use <, not <=, for its termination condition. For the various ways to loop through arrays in JavaScript, see this question and its answers.
Here's a cleaned-up version of that code:
var text, grupo, i; // Declare variables
text = {}; // Create an object and assign it to the variable
grupo = []; // Create an array and assign it to the variable
text.a = "texta"; // Set the property `a` on the object
text.b = "textb"; // Set the property `b` on the object
grupo.push(text); // Put that object onto the array
text = {}; // Create a second object
text.a = "textc"; // Set the property `a` on that new object
grupo.push(text); // Put that object on the array
for (i=0;i<grupo.length;i++) {
// ^-------------------- Note no =
console.dir(grupo[i].text.a);
}
Do you mean something like this?
for (var key in validation_messages) {
var obj = validation_messages[key];
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj.hasOwnProperty(prop)){
alert(prop + " = " + obj[prop]);
}
}
}
Reference: https://stackoverflow.com/a/921808/1054926
groupo[i] is already a text object so you there is an error there. Also, you don't want to look until your index is <= to the length.
Here is a quick look at what you may be looking for in your loop:
for (i=0;i<grupo.length;i++) {
console.log(i,grupo[i].a);
}
However you will have additional problem when you discover that the value of "a" is not what you may be expecting.
Here another possible "solution"
var text = {};
var grupo = [];
text.a = "texta";
text.b = "textb";
grupo.push(text);
text.a = "textc";
grupo.push(text);
for (var i=0;i < grupo.length;i++) {
var x = grupo[i];
if (x && x.a){
console.log(x.a);
} else {
console.log(x);
}
}

How to refer to class using variable

If I have this object:
var myclass = {
foo: {
bar: function(var) {}
},
some: {
bar: function(var) {}
}
}
and I want to call the bar function depending on a variable that defines the parent level of the object like this:
var part = "some";
myclass.part.bar(var);
How can I do?
You can do it using array access notation:
myclass[part].bar(var);
JavaScript objects are like associative arrays, and you can use a property name to either set or get the property's value, you can even create new properties with this syntax.
For example:
var obj = { a : 1 };
console.log(obj["a"]); // 1
obj["b"] = 2; // this creates a property called b and assigns 2 as the value
console.log(obj["b"]); // 2
You can keep a reference to a function as a variable, which is a little cleaner than a string.
var func = myclass.foo.bar;//or myclass.some.bar
...
func.call(myclass, var);
Or keep a reference to the part:
var part = myclass.foo;//or myclass.some
part.bar.call(myclass, var);

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.

Using variable name in JS object?

I defined a variable which will get user's input:
var input = USER_INPUT;
then, I create an object which will use this input as an variable name inside the object:
var obj = { input: Car.newCar(...)}
Then, I try to access the obj[input], but it returns to me undefined. Is it so that in javascript, I can not use variable as an object's variable name?
If I would like to define a object which has vary variable name and variable value, how can I do?
So I guess you want the store the input under a key named after the input itself.
You can assign the value returned by Car.newCar() by using the [] method:
var input = "some text";
var obj = {};
obj[input] = Car.newCar();
Sorry changed my answer after re-reading the question
var USER_INPUT = 'something';
var obj = {};
obj[USER_INPUT] = 'value';
obj.something ; //# => value
obj['something'] ; //# => value
obj[USER_INPUT]; //# => value

Javascript function push problem

i've following JS function.
responseData:function(resp){
this.jsondata = eval('(' + resp + ')');
this.propList = [];
for (var i = 0;i<this.jsondata.length;i++) {
for (obj in this.jsondata[i]) {
alert(obj); //shows the property name of obj
this.propList.push({
obj : this.jsondata[i][obj] //insert only simple obj string
});
}
}
return this.propList;
}
I want to insert in my propList the property name and the value, but instead inserting the property name this function inserts simple 'obj' as a string. What i'm doing wrong?
greetings
Stefan
Change the loop to,
for (obj in this.jsondata[i]) {
alert(obj); //shows the property name of obj
var item = {};
item[obj] = this.jsondata[i][obj];
this.propList.push(item);
}
When you use object-literal to create an object the property names are not evaluated as variables. To specify the name of an objects property using a variables current value, you must use the obj[variable] format. This will create a property within obj whose name will be the same as current value of variable.

Categories