So the problem, i have data that i call by using window.blah.blah and it will spit out info based on a user or an item in a database.
Now my problem is that i want to use the window.blah.blah with a dynamic appendage so like window.blah.blah.VARIABLE1
i have tried window.blah.blah.instances[variable] but i get a typeerror saying the value of variable is not defined (so if variable = test1 the error would be TypeError: Cannot read property 'test1' of undefined. variable is generated so it can be test1 test2 that correspond to stored objects.
if it helps i am using the call within a loop that is using it to get access a stored json obj with different object names.
also if I one of the objects is called test1 and i do window.blah.blah.test1 it accesses the object but window.blah.blah.instances[test1] gets the above error.
What am i doing wrong?
Perhaps the syntax you are looking for is window.blah.blah[VARIABLE1]
(assuming the blahs are objects.)
note that storing data on window is typically a bad idea, so for the following example, I'll move the top-level object from the global space (accessed through window) into a local variable:
var myObj = {
blah: {
blah: {}
}
};
var fooVar == 'foo';
function getMyDynamicVariable() {
return "foo"; //really this would by some dynamically generated string
}
//example usage:
myObj.blah.blah[getMyDynamicVariable()];
// OR
myObj.blah.blah[fooVar];
// would be the same as
myObj.blah.blah.foo //(in this exact example, where all functions and variables contain the string 'foo'.)
Related
I have a two-part issue.
1) I need to access a list of unique values nested within a complicated object. I am able to output the object via a console.log as such:
console.log(dataStore);
This outputs the following (in part):
`Object
getResponses: function getResponses(ids)
arguments: null
caller: null
length: 1
name: "getResponses"
prototype: Object
__proto__: function ()
<function scope>
Closure
responseCache: Object
12345: gr.Response
12346: gr.Response
etc...
getImg: function (imageId)
etc... `
I need a call that gathers the list of numeric values under responseCache: 12345, 12346, 12347, etc. The total amount of these values may very. Could be 10, could be 100 in the list.
2) I need to create a conditional statement that compares the value for a variable that is not a part of the object above. For example:
variableX = variableXvalue;
if ("variableXvalue" is one of the unique values in "responseCache") {
//then do this
}
Not sure if it matters for the purposes of the question here, but the variableX is in a loop that iterates through attributes on a page. It loops through all matching tags/attributes on a page, and needs to compare those attribute values with the full list of responseCache values each time it loops.
Thank you for considering this question.
Let's look at an example of how this sort of code could be written.
var obj = (function() {
var responseCache = {
12345: 12,
12348: 34,
12355: 56
};
return {
getResponses: function getResponses(ids) {
return responseCache[id];
}
};
})();
console.log(obj);
If you run that code in your console, you'll get able to drill down and see essentially the same output as what you're seeing. Now, how can you directly access responseCache? You can't. It's effectively private and only directly accessible from within that closure. Outside code cannot access that variable directly. You can only indirectly access it if any functions on obj use it.
function me(a, b) {
function he(c, d) {
if(!a[c]) {
}
}
}
Please someone explain 'if(!a[c])' for me.
why this square bracket is used here in [c] though it is a parameter. it is not an array obviously.
what does if(!a[c]) make sense? how two parameters are used like this?
There is nothing special about that code.
It is saying, in English, If the property c of a is falsey, then the condition is true.
In JavaScript, bracket notation can be used to access properties of an object or members of an array.
For example, someArray[5] will access the 6th member of the array, while someObject['someProp'] will access someProp of the object someObject.
The argument a is likely an object. The syntax:
if (!a[c])
Checks to see if the property in the variable c on the a object does not have a truthy value. This could be if it was null, false, undefined or any other falsey value.
The bracket notation can be used with property names. So, if you have an object like this:
var x = { name: "John"};
Then, you can access that property like in any of these ways:
x.name
x["name"];
// Or, if the property name is in a variable
var prop = "name";
x[prop]
Your example is using a version of the last of the above three options when the property name is in another Javascript variable.
In javascript, properties can be accessed dynamically using the square-bracket syntax.
Consider the following:
var person = {name:'Sarah'};
console.log(person.name); // logs 'Sarah';
Sometimes, you might want to dynamically access properties of an object, using a variable that holds the name of the property you want to access. The above example could also be written like this:
var person = {name:'Sarah'};
var prop = 'name';
console.log(person[prop]); // logs 'Sarah';
I'm trying to pass a variable to a child object of my parent object, but its returning undefined. (clearly I'm not sure how the scoping of a JS object works).
var parent = {
pid: '565',
child: {
cid: this.pid + '_child_789',
sayHello: function(){
alert('My id is ' + this.cid);
}
}
}
Calling parent.child.sayHello() logs the this.cid as undefined.
I'm (incorrectly) thinking that the child would inherit the pid property and could be referred to by this.pid, but it cannot.
Is there a way to do this without hardcoding the pid value?
I know I could do parent.child.cid = parent.pid + '_child_789' after creating the object but that is not scalable or practical for me.
You cannot access properties like that in your object literal. I would go into more detail, however, this question has already been answered several times. Please review the following questions:
JavaScript: Access own Object Property inside Array Literal
Can a JavaScript object property refer to another property of the same object?
Let's say there is a simple object literal which name will never change:
var car = {
wheels : 4,
construct : function() {
var that = this;
setTimeout(function() {
console.log(that.wheels);
console.log(car.wheels);
}, 500);
}
};
My question is: Which way is better? Referencing by the object's name or creating a new variable (which may take some time and memory and probbaly must be done in multiple functions)?
Within the object, you should always refer to the object via this (or a copy of it, e.g. that, if required) to prevent the following breakage:
var car = ...
// do stuff
car = undefined; // or anything else, perhaps by a code hacker in the JS console
// class is now broken
You should treat the variable name that happens to have been given to your object on the outside as unknown to you, and subject to change.
Someone else might call it something else, there might be multiple names, the name might suddenly point at some other object altogether. Such variables are for the benefit of the "owners" of references to the object, and not for the object itself.
i am trying to get a value from a key stored on a string variable proyNombre, but whenever i call it via the common method "myAssociativeArray.MyKey", it gets the variable 'proyNombre' as the key, instead of getting its value and passing it as a key.
proyectos.each(function(index){
var proyNombre = this.value;
if(!(proyNombre in myArray)){ // whenever the variable is undefined, define it
myArray[proyNombre] = horas[index].value-0 + minutos[index].value/60;
}
else{
console.log(myArray.proyNombre); //This doesnt work, it tries to give me the value for the key 'proyNombre' instead of looking for the proyNombre variable
console.log(myArray.this.value); //doesnt work either
}
});
Try:
console.log(myArray[proyNombre]);
myArray is actually an object in javascript. You can access object properties with object.propertyName or, object['propertyName']. If your variable proyNombre contained the name of a property (which it does) you can use the second form, like I did above. object.proyNombre is invalid - proyNombre is a variable. You can't do for example:
var myObject = {};
myObject.test = 'test string';
var s = 'test';
console.log(myObject.s); // wrong!!
but you could then do:
console.log(myObject.test);
console.log(myObject['test']);
console.log(myObject[s]);
You need to use the same syntax you used to set the value:
console.log(myArray[proyNombre]);
Simply access the value with myArray[proyNombre].
You're doing it right in the assignment: myArray[proyNombre]. You can use the same method to retrieve the variable.
If you change:
console.log(myArray.proyNombre);
console.log(myArray.this.value);
to
console.log(myArray[proyNombre]);
console.log(myArray[this.value]);
You should get the same value (the value for the key represented by the variable proyNombre) logged twice.
It's true that Javascript doesn't have associative arrays but objects in Javascript can be treated like associative arrays when accessing their members.