How to use an array in a for of loop?

1076 views javascript
0

We normally have this code

var array1 = ['a','b','c'];
for (const [i, value] of array1.entries()) {
   console.log(i, value);
}

Works great but I want [i, value] to be dynamic.

var array1 = ['a','b','c'];
var keys = ['smith', 'bob']
for ( keys of array1.entries()) {
   console.log(smith, bob);
}

It does work if I console keys[0] but is there a way to get the value as keys (without indexOf trick)

answered question

Why do you want the variable names to be dynamic? Whatever you call them, they'll still be a key/value pair.

"without indexOf trick". What indexOf trick?

@NicholasTower this might be a bad way of trying to replicate the v-for attribute from vuejs but now that I hit this wall I am interested if it can be done. Basically, I'm trying to say "it doesn't matter, I just want to know" in a polite way :)

@relidon the reason i want clarification is that this seems like an XY problem. You have some problem X that you want to solve, and you think that dynamically assigning variable names (Y) is the way to do it, so you ask us about Y. To the rest of us, we're scratching our heads trying to figure out why you want to do Y. I can come up with hacky approaches with eval that would do Y, but they are almost certainly not the correct advice to give you.

@ibrahimmahrir I thought it could be done with indexOf but I don't think it can. Sorry for any misleading

1 Answer

3

I'm not sure exactly what you mean by dynamic, but perhaps a simple JavaScript object could work for mapping a key-value pair?

var values = {'smith': 'a', 'bob': 'b'};
for (var key in values) {
  console.log(values[key]); //outputs all values in object
  console.log(values['smith']); //outputs 'a'
}

posted this

Have an answer?

JD

Please login first before posting an answer.