I am trying to call an object.
The way I am currently doing it:
var key = object_0
The way I'd like to do it
var key = "object_" + questionId;
But when calling the concatenated object_0 I do not get the object info
when I do a:
console.log(key)
Any insight would be awesome.
Short answer: global scope + brackets.
window['object_'+questionId] = 'foo';
console.log(window['object_'+questionId]); // 'foo'
Long answer: Use dynamic variable names in JavaScript
If you use ES5 you can do so with creating new empty object. Here are the steps:
1.create empty object
var o = {};
2. use brackets to produce the new key on an object - ("object_" + questionId) - this will force the parser first to evaluate expression in the brackets
3.assign value to a newly added key
o[("object_" + questionId)] = XXX;
Then console.log(o) will output {object_0: XXX}
You can use the window object (access to global variables only):
var object_0 = { p: 42 },
questionId = 0,
key = "object_" + questionId;
document.write(window[key].p);
But i suggest to change the data structure to a more concise style:
var questions = { 200: { p: 42 }},
questionId = 200;
document.write(questions[questionId].p);
Related
If you have a javascript variable that is an object and you make a new variable equal the the first variable, does it create a new instance of the object, or do they both reference the same object?
They always reference the same object. We can see that by trying the following:
var x = {foo:11};
var y = x;
y.foo = 42;
console.log(x.foo);
// will print 42, not 11
Object Reference explained!
Look the image for better understanding. When you create an object, suppose s1 it is having just a reference in the memory heap and now when you create another object say s2 and say s1 = s2 that means both the objects are actually pointing to the same reference. Hence when you alter either of them, both change.
Both will refer to the same object.
If you want to create a new instance:
var Person = function() {
this.eyes = 2,
this.hands = 2
};
var bob = new Person();
var sam = new Person();
Those two are different objects.
Here is the answer: when you create an object and then assign it to another it will refer to the same object.
Here is an example:
var hacker = {
name : 'Mr',
lastname : 'Robot'
};
console.log(hacker.name + '.' + hacker.lastname);
// Output Mr.Robot
// This variable is reference to hackers object
var anotherPerson = hacker;
console.log(anotherPerson.name + '.' + anotherPerson.lastname);
// Output Mr.Robot
// These will change hacker object name and lastname
anotherPerson.name = 'Elliot';
anotherPerson.lastname = 'Alderson';
console.log(anotherPerson.name + ' ' + anotherPerson.lastname);
// Output "Elliot Alderson"
// After it if you try to log object hacker name and lastname it would be:
console.log(hacker.name + '.' + hacker.lastname);
// Output "Elliot Alderson"
You can check the link here and play with it. It is not to complicated.
JSBIN Object Hacker
If you mean something like this
var a = { foo: "foo" };
var b = a;
then yes. They reference the same object.
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }
I have separate javascript files to load custom objects; these objects are designed to extend some default parameters when the main function is read
they each look like
var str1= { path:'url1:, var1:5};
var str2= { path:'url2:, var1:3};
etc...
I have an array of strings(that is generated from loading an rss page) and i want to return the object based on if its name matches the object name. hardcoding it would kind of defeat the purpose
Take a look at this question. It shows how to reference objects by using strings. The only difference I can see is that rather than starting with the window object, you would start at whatever object defines your current scope (e.g. this).
You can use the square bracket notation to refer to object properties whose key name is held in a variable:
var key = 'path';
var str1 = { path: 'url', var1: 1};
var value = str1[key]; // value == 'url';
You can also do:
var str1 = 'a';
var str2 = 'b';
var key = 'str1';
var value = window[key]; // value == 'a';
var map = { "string1": { path: "url1", var1:5},
"string2": { path: "url2", var1:3} };
...
var url = map[yourstring].path;
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];
});
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }