To start I have a few different objects made from a constructor named Pad.
For example I have objects named: padQ, padW ,padE …ect
Each one of these objects I have the property (.keyID).
For example when I call padA.keyID I get a number, when I call padB.keyID I get a different number.
In the example code below the first property number is the keyID property. Ex. padQ.keyID = 113
var padQ = new Pad(113, 'Q', 'Beat Box Kick');
var padW = new Pad(119, 'W', 'Funky Bass');
I am trying to make a loop which concatenates strings to output the keyID property for each pad.
var keyArr = ['Q', 'W'];
for(let i = 0; i < keyArr.length; i++) {
var str ='pad'+keyArr[i]+'.keyID';
console.log(str);
};
The above code outputs the strings ‘padQ.keyID’ and ‘padW.keyID’ but I want the value stored in these properties instead.
How do I do this?
You can’t really dynamically build variable names.
Put all of them in another object when you’re building them up in the first place, like: pads = { padQ: { keyId: ...
Then you can just access values via pads[key].keyId
or whatever
Why not just create a pads object which uses the letters as property names with a Pad as the property value?
var pads = {
Q: new Pad(113, 'Q', 'Beat Box Kick'),
W: new Pad(119, 'W', 'Funky Bass')
}
for (let letter of ['Q', 'W']) {
console.log(pads[letter].keyID);
};
You may not even need to store the letters (i.e ‘Q’, ‘W’, etc.) as Pad properties using the above.
EDIT: @DanCouper beat me to the answer.
I guess technically you could use eval.
var keyArr = ['Q', 'W'];
for(let i = 0; i < keyArr.length; i++) {
var str ='pad'+keyArr[i]+'.keyID';
console.log(eval(str));
};
Thanks! Thats much easier.
You would need to be very careful using eval when using anything from a user.