Using variable name in JS object? - javascript

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

Related

How to fetch a value from JavaScript array?

I have a JavaScript array and I want to get the value of last name from it.
Can anyone tell how to get that from this array example:
var result = [{"FirstName":"paapu","LastName":"gandhi"}];
You have an array containing an object, so you have to retrieve the object by doing:
var myObj = result[0]
And then get the LastName property by:
var lastname = myObj.LastName
Get the first object.
var obj = result[0];
Refer to the property of the object:
var prop = result[0].FirstName;
If property name comes dynamically, that is, from a variable, use square bracket notation.
var myVar = "FirstName";
var prop = result[0][myVar];

javascript access object with variable name

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

Use variable for property name in JavaScript literal?

I know we can create new properties in Javascript objects during runtime but could that property be assigned a value too? For example.
var value = "New value";
var table = new Object();
var newValue = table[value];
Now, I know that value table has a new property called "value". but does that "value key contains the information as " New Value". So, does that mean now table object is like following:
table = {
value:"New Value";
}
You're confusing accessing with assigning.
// Assigns a variable named 'value' with a value of 'New Value'.
var value = "New value";
// Creates a variable named 'table' as a blank Object.
var table = new Object(); // Alternatively - table = {};
// Attempts to access "New Value" from object "table" which returns undefined.
var newValue = table[value];
If you want to assign properties to an object you do so like this:
// Assumes table is still an object.
table['key'] = 'value';
// Note that I almost _always_ opt for the variable['key'] notation over
// the variable.key notation because it allows you to use keys
// that would otherwise not be valid as identifiers.
table['Some Key'] = 'Some Value'; // This works.
table.Some Key = 'Some Value'; // This does not.
Later, when you want to retrieve that value and store it in a new variable, that's when you do this:
var newVariable = table['key'];
Hopefully that clarifies some. Please let me know if I can expand on any part of it.
no. your statement
var newValue = table[value];
is not setting anything, and since at the time when you created table you didn't assign any property, newValue will be undefined.
If you have a value variable that is assigned a value, and you want to assign that value to table under the key value, you want to do
table['value'] = value;
or alternatively
table.value = value
Erm, no, I don't think you've got it quite right.
All that does is assign undefined to newValue, because you're trying to access table's "New Value" property, which doesn't exist.
What I think you're trying to do is this:
var value = "New value";
var table = {};
table.value = value;

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.

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