I'm pretty sure this question is going to get negative response as many people have already asked it in SO. But trust me I have read every single answer of every single question none helped.
I know that in jquery you can put the array key name dynamically like this: somearray1["abc" + variable] but I'm not looking for that. I want to call the array name dynamically like:
var i=1;
console.log( "somearray" + i["abc" + variable] )
Can someone tell me how is it possible? I cannot put it in another array and call that as I'm building a very dynamic script, so I must need to call the array name dynamically.
Any help will be highly appreciated.
Normaly, your array depend from this.
this["somearray" + i]["abc" + variable]
var bob1 = [1,2,3];
var name = "bob";
console.log(this[name+"1"][0])
I'm not sure exactly what you're asking here from your example. Do you want to console.log the value held at a dynamically changing position of "somearray"? If so, array positions are numerical indices (e.g. somearray[1]) and cannot be accessed via strings.
Are you trying to access an object property (e.g. someObject1["abc" + variable]) alternatively?
If it's an object property you are trying to access with changing parameters, you might want to try using ES2015 template literal syntax.
let i = 1;
let someObjectName = `someObject${i}`;
console.log( someObjectName[`abc${variable}`] );
That way the concatenation of the object name and its property will happen dynamically. I hope this helps.
Related
I have name that I get from component(for example "popular" and I get it by "this.props.name") and I need to push that name in this structure: "this.props.{name which I get} => this.props.popular", but I don't know how I can do this.
I tried do this:
let needName = this.props.`${this.props.name}`;
But it didn't work. I know that it's strange question but I need to solve it by this way.
If you're trying to use a variable to dynamically create the reference to a property in an object, you can use bracket notation:
let needName = this.props[this.props.name];
For more information, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties
I have two variables with JSON files. The first is a list of keys looks like this:
keylist = ["key1","key2","key3"]
The second one is generated from a database and looks like this:
data = {
"key1"{
#further data
},
"key2"{
#further data
},
"key3"{
#further data
}
}
Now I want to access the second element of the database with the key from the keylist
data.keylist[1];
Which doesn't work because the return of keylist[1] is a String? I did some research and the use of the window function was proposed. So I tried this:
window["data." + keylist[1]]();
Which leads to a "is not a function" error. What can I do to solve this problem?
As simple as that:
const mydata = data[ keylist[1] ];
Also, your code is correct from the point of syntax, but it tells completely different than you expect it to tell.
data.keylist[1];
tells JS that you expect to have an object called data which has a property called keylist and which is (most likely) type of array, and you want to get the second element of this array.
PS: And one more point here. Your question title is not completely correct because of the difference between Arrays and Object in JS.
There is no "string keys" for arrays in JS, so you cannot "access array with a string key". Well, truly speaking there are, but not for items of array. Array items only have numeric index, which you can use to access it. Objects, in contrast to arrays, may have named properties. So when you see something like that: data = myVar['data'], you can tell that you're dealing with an object, while data = someVar[0] can be both, an Array (most likely) or also an Object with key named '0'.
I don't think the issue you're having with your first example is because it returns a key. I believe the issue is because data doesn't have a property called keylist. Instead of that, try it as
data[keylist[1]]
and see if that works for you. The reason this one should work is that, in this situation, Javascript will evaluate the string return of keylist[1] and then use it as a string index for the data variable. Let me know if this works out for you :D
You can try using using something like this.
data[keylist[1]]
finalVariables() returns an object that contains data accessible by .dataName notation i.e. finalVariables().mainViewWindow0 returns the string stored for mainViewWindow0. I'm trying to access mainViewWindow0 using a dynamically created variable, but for obvious reasons this doesn't work so well with dot notation, but I don't know how to work around it. Help to be had for me?
Please ignore the poor coding practice of having a hard-coded number in there; I promise to get rid of it later
activePane = dot.id.substring(6); //gets dot # and sets it as active pane
var tempForPaneNumber = "mainViewWindow" + activePane + "";
document.getElementById("mainViewWindowContent").innerHTML = finalVariables().###this is where I want to use
the string from "tempForPaneNumber" to access ###
finalVariables[tempForPainNumber]()
Should do the trick if I understand correctly.
In Javascript you can access properties of an object either through the dot notation or through the use of brackets to specify the identifier for the property so myVar.foo is equivalent to myVar['foo']. Therefore, if I understand what you are asking correctly you want to use finalVariables()[tempForPaneNumber]()
Right, so I have a number of Backbone models going on, and in one of them I have an object that has a set of keys and values, of which the values are modified by locating the key from a string.
So I started out with code that was built on the below principle, I am quite comfortable with how and why this code will output true:
var boundData = {
text: 'value'
}
var key = 'text';
return (boundData[key] === 'value');
So to set the value of the property, I would do something like:
boundData[key] = 'new value';
Then I decided to translate all of my existing classes to Backbone models. And the problem that I hit, was that I can no longer change my properties with an equals operator, instead I use the set method provided by Backbone for models. This method takes a string as the first parameter, this string identifies the key for the variable that I am trying to change.
this.set("boundData[" + settings.name + "]", new OpenCore.boundData(settings));
This does not seem to work, and neither does this:
this.set("boundData." + settings.name, new OpenCore.boundData(settings));
SOLVED IT. Whilst I was writing out the question, I figured out a way to do it. But thought I would leave it here in case others run into the same problem.
This is a solution, whilst it may not be the best (I'd be interested if someone could get the original way sorted.), but it seems to work.
var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);
Hope this helps someone else out!
This is a solution, whilst it may not be the best (I'd be interested if someone could get the original way sorted.), but it seems to work.
var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);
Hope this helps someone else out!
I'd really like to track variables without switching between Firebug console windows or clicking around so much, so I want to draw a runtime viewer of variable names and their corresponding values that will display on the page of the app I am building.
I'd like to two functions, show(variableName) and freeze(variableName). They will output both the variable's value and the name of the variable or object as a literal string which will serve as the text label in the viewer. freeze(variableName) is the same as show(variableName) except with a setTimeOut timer for tracking loops.
I'm sure I'm missing something basic, but I haven't found out a way to get the string that comprises the name of a value programmatically so I can use it as a label. I guess I could create the table with hardcoded labels prior to runtime and just populate it with values at runtime, but I really want to generate the table dynamically so it only has those variables I specifically want to show or freeze. Simple functions:
foo1 = "Rock";
show(foo1);
foo2 = "Paper";
show(foo2);
foo3 = "Scissors";
show(foo3);
should output this via getElementById('viewer-table'):
<table>\<tr><td>foo1</td><td>Rock</td></tr><tr><td>foo2</td><td>Paper</td></tr><tr><td>foo3</td><td>Scissors</td></tr></table>
I've tried this solution:
How to convert variable name to string in JavaScript?
and eval() but it's not working for me...I dunno, shouldn't this be easy? Getting frustrated...
Thanks,
motorhobo
I am not sure you can actually get the "name" of the variable that is being passed into a function for two reasons:
1) The variable is just an identifier. In fact, you could have multiple identifiers reference the exact same object. You are (generally) passing that reference, not any actual object.
2) The show/freeze function is going to stomp on the identifier name, either through named arguments in the function declaration or by referencing them through the arguments array.
I was trying to think if there was some clever way to use the arguments.callee or the stack property on an exception in Firefox... but I can't see anything that would expose the arguments as you desire.
What I would recommend is to simply add the name of the variable and its value to a simple object, and call one of the various jsDump methods (I prefer the one in QUnit):
function show(o) {
document.getElementById("viewer-table").innerHTML = QUnit.jsDump(o);
}
// actually use the method
show({"foo1":foo1});
There's no easy way to solve this as the called function simply doesn't know the original name of the variable. You couldn't solve this with reflection even (esp. in javascript) so you'll have to pass the name of the variable to the function too. To follow the link you posted:
function show(varObject)
{
for(name in varObject)
{
alert(name + ": " + varObject[name]);
// save both name and reference to the variable to a local "to observe array"
}
}
And call it with
var test = "xxx";
show({'test' : test});
Within the for loop you could add easy variable to a monitor array and update your gui in fixed time intervalls (you can't be notifed when a signle variable changes it's value. You need some kind of global monitor/observer which exactly you're trying to create).