Get value from dynamic variable [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 5 years ago.
I have variables such as app.figures.data[0].user.x0 , app.figures.data[0].user.y1, and app.figures.data[0].user.d2. These variables were assigned values.
There are a dynamic number of these variables following the order of incrementing the final number in the variable (ie: The next variable after app.figures.data[0].user.d2 is app.figures.data[0].user.x3).
I am trying to determine an efficient way to get the value of each variable dynamically in a loop.
for(j = 0; j < len; j++){
var x = 'x' + j;
j++;
var y = 'y' + j;
j++;
var d = 'd' + j;
var dresult = app.figures.data[0].user.d;
}
I need the value of dresult as it was for app.figures.data[0].user.d2. For example, app.figures.data[0].user.d2 is 23 so dresult should be 23 on that iteration.
I am new to JS so any suggestions are appreciated.

Would the [] operator work for you?
for (let j = 2; j < len; j += 3) {
let dresult = app.figures.data[0].user['d' + j];
}

var values=["x0","y1","d2"]. map(el=>this[el],app.figures.data[0].user);
It will map the keys to their corresponding values.
You can put that in a loop:
for(var i=0; i<100;i+=3){
var values=["x","y","d"]. map((el,id)=>this[el+(i+id)],app.figures.data[0].user);
values.forEach(console.log);//just an example case
}
Some explanations: i is the counter, incremented by 3, stops at 102. el is an array element, so "y", and id is the index in that array. this is the user object. So this[el+(i+id)] gets the value of this objects property.
By the way dynamic variable names are really bad style and will cause many bugs. May change your code to work without it.

Related

When using strings with numbers at the start in an array key (Indesign 2017, extendscript) they don't get added to the array

Observe:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
The actual result in extendscript would be ... grouplinks ... empty.
If I would change this example to be:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
It would work perfectly. The only change is the missing "59" at the start of the string used for the array key.
Note that this works perfectly when I run it in console for chrome or firefox. It seems to be indesign and/or extendscript fooling around.
Anything have any ideas why ? I've meanwhile worked around the problem but I'm intrigued.
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
That's exactly what it does, but the way you're viewing the data is likely concealing it because you're not using the proper data structure. Also, property access won't work without using [] because identifiers may not start with a number, so you'd need:
groupedLinks["59notgonnawork0"]
What you're doing isn't meant for arrays, which are expecting sequential numeric indices (though they can technically be assigned other properties too). The type of structure you should be using is a plain object instead.
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
const linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array; // Array? plain Object? Depends on its use.
}
Why not trying to push the value in the array on each iteration.
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks.push(linkName);
}
ExtendScript Arrays are great for stocking data per indeces. If you need key/values objects, why not use… Objects ?
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = "Whatever…";
}
alert( groupedLinks["59notgonnawork0" ] ); //"Whatever…"

Print all the names of keys stored in localStorage html [duplicate]

This question already has answers here:
Get HTML5 localStorage keys
(15 answers)
Closed 7 years ago.
I'm trying to print the names of all the keys stored in localStorage with each key in a separate line. This is my code:
function viewsaved(){
$('#saved').show();
var stuffsaved = Object.keys(localStorage);
var splitit = stuffsaved.split(',');
for (var i = 0 ; i < splitit.length ; i++ ){
$('#saved').append(splitit[i]+"<br>");
}
}
when I call the function, it does nothing.
How do you do this properly?
Object.keys returns an array, not a string. Just modify slightly:
var stuffsaved = Object.keys(localStorage);
for (var i = 0 ; i < stuffsaved.length ; i++ ) {
$('#saved').append(stuffsaved[i]+"<br>");
}
If you have or expect a lot of keys, I would suggest building the list in a temporary variable first to avoid frequent DOM update, for example:
var keys = Object.keys(localStorage);
var list = "";
for (var i = 0 ; i < keys.length ; i++ ) {
list += keys[i] + "<br>";
}
$('#saved').append(list);

Object's push method not working properly [duplicate]

This question already has answers here:
Javascript Object push() function
(10 answers)
Closed 8 years ago.
I have a object for which i am using push method and it gives me length one more than expected.
var Object=[];
var temp = {};
var j=0;
while(j<2){
temp.id= j+1;
//other properties setting
Object.push(temp);
j++;
}
console.log(Object.length);
gives me 3. Also I see three object values, first as empty second has id =1 and third has id =2.
.push is a function of Array and not Object and don't use variable names that cause ambiguity.
Use:
var arr = [];
var temp = {};
var j = 0;
while (j < 2) {
temp.id = j + 1;
//other properties setting
arr.push(temp);
j++;
}
console.log(arr.length);

How to dynamically create variable name?

I need to create javascript objects that base on user defined number. So if user defines 20, then I need to create 20 variables.
var interval_1=0, interval_2=0, interval_3=0, interval_4=0, interval_5=0... interval_20=0;
how do I do it so the name of the object can be dynamically created?
for (i=0; i<=interval; i++){
var interval_ + i.toString() = i;
}
Erm, use an array?
for( i=0; i<=count; i++) array[i] = i;
Use an array:
var i, count, interval = [];
// user defines count, 20 for example
count = 20;
for (i = 0; i < count; i++) {
interval.push(i);
}
// interval[0] === 0
// interval[19] === 19
// interval.length === 20
Note, this starts the index at 0 and goes up to count - 1. Do not use i <= count unless you start i at 1.
Here is a jsFiddle to illustrate. Hit F12 to open dev tools in most browsers and look at console, or change console.log() to alert().
Link: http://jsfiddle.net/willslab/CapBN/1/
Alternatively, you could setup a single object with properties for each value:
var i, count, intervals = {};
count = 20;
for (i = 0; i < count; i++) {
intervals["interval_" + i] = i;
}
//intervals.interval_0 === 0
//intervals.interval_19 === 19)
Link: http://jsfiddle.net/willslab/EBjx7/2/
for (i=0; i<=20; i++){
window["interval_" + i.toString()] = i;
}
Javascript variables can be created by:
a variable declaration, e.g. var x;
assigning a value to an undeclared variable, e.g. y = 'foo';
an identifier in a formal parameter list, e.g. function bar(x, y, z);
using eval, e.g. eval( 'var x = 4');
If all else fails and you want say 5 variables, you can do:
var s = [];
var i = 5;
while (i--) {
s[i] = 'a' + i;
}
eval('var ' + s.join(',') + ';');
alert(a0); // shows undefined
If a0 wasn't defined, the last step would throw a reference error.
Of course the issue you now have is how to access them. If they are created as global variables, you can use:
globalObj['a' + i];
where globalObj is usually window, however there is no equivalent for accessing function variables since you can't access their variable object.
So the usual solution is to put things into arrays or objects where you can iterate over the properties to find things you don't know the name of.

Using numbers for names of javascript object elements

Is the following code valid?
var i;
var objs={};
for (i=0; i <10; i++)
{
objs.i=new FooObject();
}
alert(objs.4.someMethod());
If not, how should it be rewritten to accomplish what I want?
You should edit your code as following:
var i;
var objs = {};
for (i = 0; i < 10; i++) {
objs[i] = new FooObject();
}
alert(objs[4].someMethod());
var i;
var objs = new Array();
for(i = 0; i < 10; i++)
{
objs.push(new FooObject());
}
objs[4].someMethod();
You cannot use numericals for variable names 1. If you want to reference an item by a numerical value, use an array 2. You can then access items by their key in the array. If you want to cycle through, you can use the for...in option 3. It won't matter if your keys are sequential and contiguous:
var x;
var myItems = new Array();
myItems[0] = "Foo";
myItems[9] = "Bar";
myItems[5] = "Fiz";
for (x in myItems) {
alert(myItems[x]);
}
1 http://www.w3schools.com/js/js_variables.asp
2 http://www.w3schools.com/js/js_obj_array.asp
3 http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_for_in
You can't use numbers as variable names, because straight up numbers exist as their own object set in Javascript (i.e, you could think of 4 as already being a global variable that you can't override).

Categories