0

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.

John
  • 93
  • 2
  • 8
  • Why do you need to increment `j` from _inside_ the loop? Also, post the whole code, including HTML, please. – apires May 25 '17 at 14:40
  • Is `app.figures.data[0].user` an `Object` can't you simply use `Object.keys`? – Diego May 25 '17 at 14:41
  • @doutriforce Because I need to `app.figures.data[0].user.x`, `app.figures.data[0].user.y`, and `app.figures.data[0].user.d` to use at one time. – John May 25 '17 at 14:42
  • @Diego Can you please elaborate? An example would be helpful. Thanks – John May 25 '17 at 14:43
  • @john yes an example would be really helpful – Jonas Wilms May 25 '17 at 14:45
  • I have probably misunderstood your problem. Your issue is not with the variable names, it is with accessing them ordered. So nothing to do with `Object.keys`. – Diego May 25 '17 at 14:53

2 Answers2

1

Would the [] operator work for you?

for (let j = 2; j < len; j += 3) {
  let dresult = app.figures.data[0].user['d' + j];
}
PeterMader
  • 6,987
  • 1
  • 21
  • 31
0
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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151