Dynamic array names in jQuery [duplicate] - javascript

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
I have an array that holds several values. I have several other areas, each with a different number instead of the
var u3s0A = ["Ques De Ti", "Encina", "Renaissance", "Syllabic", "Polyphonic", "None"];
However, I was unable to figure out how to refer to the arrays dynamically. I tried doing:
alert(u3s + randomNumber + A[p]);
but only got errors. I realize that if i do
alert('u3s' + randomNumber + 'A'[p]);
it outputs the correct array name, but it is then transformed to a string and when I index it:
var arrayHolder = 'u3s' + randomNumber + 'A';
alert(arrayHolder[0]);
I get the first number in the array name (u), not the first item in the array.
Any help would be appreciated!
Thanks so much for your time.

Try this way, creating a temporary object and set the arrays as properties of the object and then access it using the bracket notation with the constructed property name:
var ob = {};
ob.u3s0A = ["Ques De Ti", "Encina", "Renaissance", "Syllabic", "Polyphonic", "None"];
ob.u3s1A = ["Ques De Ti", "Encina", "Renaissance", "Syllabic", "Polyphonic", "None"];
.....
and then
alert(ob['u3s' + randomNumber + 'A'][p]);
If this is in global scope and if you are in browser you can access it with window object with the same way as above instead of the temp object ob.
Demo

Try something like this:
window['u3s' + randomNumber + A[p]]

Related

How to get the value of a variable from a object in JavaScript? [duplicate]

This question already has answers here:
Javascript: How to use Template Literals with JSON?
(4 answers)
Closed 2 years ago.
I am having the object config and when I fetch the config["RegionId"], it will give me ${Region}. Now I want to fetch the value of Region. As I have got ${Region}, I thought I could do console.log(`${val}`) to get 'abc'. But it is not working.
How to get this? This is what I have tried,
var config = {
"RegionId" : "${Region}"
}
var Region = 'abc'
var val = config['RegionId']
console.log(`${val}`)
Don't put double quotes around the property value. Use back-ticks (for template literal strings) as you are doing for val. And make sure you've declared Region prior to attempting to access it.
var Region = 'abc';
var config = {
"RegionId" : `${Region}`
};
var val = config['RegionId'];
console.log(`${val}`);
And while your question is centered around template literals, I hope you know that for this scenario, they add no value and are overkill. Here's the same thing with regular strings variables:
var Region = 'abc';
var config = {
"RegionId" : Region
};
console.log(config['RegionId']);
try using eval function
var config = {
"RegionId" : "${Region}"
}
var Region = 'abc'
var val = config['RegionId']
console.log(eval("`"+val+"`"));

Can I use an expression as an array index in javascript?

Ok folks, I am trying to copy a section of a large array into an array of objects. The large array is a row from a google sheet which represents RMA data. The small array contains several (circuit) board objects. I am reading 4 items from the large array into each 'board'. To read the correct item from the large array, I need to increment the operator before reading into a new named property in my object within my small array. If I was using an array for 'board' it would be easy: create a sub loop and increment the index at each iteration. But because I'm using an object, I don't know how to do it. I tried to use an expression in my index (see code). Also, btw all this is happening inside a larger object designed to read in multiple rows from a google sheet and process them. Here's the code:
board:
[
{
code: "Board Code",
software: "S-Ver",
problem: "Problem",
riu: "RiU",
msqNotes: "MSq Notes"
}
],
grab: function (rowArray, board)
{
rma.timestamp = rowArray[1];
rma.guidelinesAgree = rowArray[2];
rma.expediteyn = rowArray[3];
rma.contact.name = rowArray[4];
rma.contact.coName = rowArray[5];
rma.contact.emailAddr = rowArray[6];
rma.contact.telNum = rowArray[7];
rma.contact.shipAddr = rowArray[8];
var boardArray = rma.createBoardArray();
var boardStartIndex = 9;
for(i = 0; i< 5; i++)
{
var k = i + 1;
board.push()
board[k].code = rowArray[boardStartIndex + 4i]; //prob here
board[k].software = rowArray[boardStartIndex + 4i + 1];
board[k].problem = rowArray[boardStartIndex + 4i + 2];
board[k].riu = rowArray[boardStartIndex + 4i + 3];
board[k].msqNotes = "";
}
Note: In Google script editor, when I try to debug, I get the error: "Missing ] in index expression." at the line that I've labeled "//prob here" above.
Another Note: I am using an expression 'k' for the index, because I have purposely initialized the 'board' array with a board[0] that contains title values.... I want to create a google doc afterword with a table that has the first row full of titles/labels for each column, and I am using the first object to store those titles. Previously I was using "board[i+1].code =" etc.
IS THERE A WAY TO USE AN EXPRESSION FOR AN ARRAY INDEX THAT IS KOSHER IN JS?
This is a syntax error:
rowArray[boardStartIndex + 4i]
I'm guessing you meant this:
rowArray[boardStartIndex + 4 * i]
I know in math & science "4i" means "4 times i" but in Javascript you have to use the "*" operator.

How to access a javascript object's property, when it has a dynamic number as property title?

I have an object which contains a variable number of arrays. The property title always is a number (like here: 15, 117). I could simply access the arrays with names[15] or names[117], but those values are changing constantly because of a data-request.
How can I access them as "the first" or "the second"???
var names = {
15: Array[1];
117: Array[1];
};
If this isn't working, I tried a for...in loop to store the arrays in variables, but it didn't really work out:
var name1, name2;
for(var key in names){
if(name1){name2 = names[key];}
if(!name1){name1 = names[key];}
}
As soon as there are more arrays, it's overriding name1 with name2 and so on...
Any idea how to solve this? Thanks already for your time.
I deleted my earlier answer, as i think is not accurate. js fiddle
var names ={1: ["a","b"],2:["c","d"],3:["e","f"]}
var nameArr=[],i=0; for(var key in names){ nameArr[i++] = names[key]; }
for(i=0;i<nameArr.length;i++)
alert(nameArr[i]);
There is example, how you can access to properties of your object with loop: http://jsfiddle.net/Y7mHB/
var names = {
15: '15',
117: '117'
};
for(var key in names) {
alert(key + ' ' + names[key]);
}
Yes that's absolutely true to access them like this. My problem is, I have to store them separately as variables, to then pass them to a function who could look like this:
var a = name[key];//the first object-property (how to store??)
var b = name[key];//the second object-property (how to store??)
function doSomething(a,b){
//do something usefull
}

Is there a way to make a dynamic variable name based on the value of another variable?

Is there a way to make the value of a variable the name for another variable? For example, I want the variable name (value_of_i) to be what ever number "i" is during that iteration. The while loop below is not what I'm using it for, it's just to explain what I'm asking.
var i = 1;
while(i<10)
{
var value_of_i = "This loop has ran " + i + "times.";
i++;
}
For the first iteration, "i" is equal to 1 so I would want the variable name to be "1":
var 1 = "This loop has ran " + i + "times.";
And the second interation:
var 2 = "This loop has ran " + i + "times.";
Yes. Using bracket notation (Here is a tutorial in MDN)
Here is a working fiddle
When doing something like containingObject[stringVariable] you are accessing the property in containingObject whose name is the value stored in stringVariable.
// this assumes browser JavaScript where window is the global namespace
// in node.js this would be a little different
var i=0;
while(i<10){
window["counters"+i] = "This is loop has ran " + i + "times.";
i++;
}
console.log(counters3);
If you'd like you can use this instead of window, however this might fail in strict mode.
Here is the main explanation of how bracket notation works from the MDN link above:
Properties of JavaScript objects can also be accessed or set using a bracket notation. Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:
myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;
You can also access properties by using a string value that is stored in a variable:
var propertyName = "make";
myCar[propertyName] = "Ford";
propertyName = "model";
myCar[propertyName] = "Mustang";
You can't make a variable name a number, its not a valid name. So var 1="" is invalid.
But to dynamically set the value you can do
var x = "variablenamehere";
window[x] = "variablevaluehere";
Thats the same as
var variablenamehere
except that it will be scoped as a global variable and will be accessible everywhere, rather than being limited to the current function scope.
Why not store your strings in an array that is indexed by i?
That way you can reference them later efficiently and easily;
var loopI = new Array();
for(var i = 0; i < 10; ++i) {
loopI[i] = "This loop has ran " + i + "times.";
}
This works:
var o = {};
var d = "dog";
for (var k = 0; k < 5; k += 1) {
o[d+k] = k*100;
}
console.log(o.dog3); // 300
This comes closer to doing what you want:
var N = {};
var M = {};
var i = 1;
while(i<10)
{
N[i] = "This loop ran " + i + " times.";
// Or, so you can use dot notation later:
M['OO'+i] = "This loop ran " + i + " times.";
// Those are capital O's, not zeros. Numbers won't work.
i++;
}
console.log(N[3]); // This loop ran 3 times.
console.log(M.OO7); // This loop ran 7 times.
The 'OO' notation could cause bewilderment and wasted time for others trying to use your code; but it could also be a source of amusement for them. This reminds me of a chess board after white's first two moves are to bring out a knight and then put it back. The board then seems to show that black moved first, and some people will endlessly insist that the configuration proves there was illegal play unless someone tells them what happened.

JavaScript acrobatics: How to declare an array, elements, and properties in one string

Given the following code:
eval('(mapping.' + binding.field + ' = eval("extVar") )');
where binding.field = "LPP[0].price" (a string) and
extVar is the same value of "LPP[0].price"
How could you program the statement above to end up with:
mapping.LPP[0].price = LPP[0].price;
when mapping.LPP isn't defined yet? This code cycles through the Microsoft JQuery templates pulling variable names as strings from the tempaltes. When we reference properties in arrays, it throws up based on this code. It says that mapping.LPP[0] isn't defined.
if(!mapping.LPP) mapping.LPP = [];
mapping.LPP[0].price = LPP[0].price;

Categories