Reputation: 14882
I have a JS Object:
var testObj = new Object();
that has a property called volume1, so
testObj.volume1
has a value. How would I go about accessing that property by using something along the lines of
testObj.volume + "1"
To give it more context, the object actually has more properties, like
testObj.volume1, testObj.volume2 and testObj.volume3
and I want to access them using some iteration. I've tried playing with the window[]
element, but have had not much success.
Thanks!
Upvotes: 3
Views: 206
Reputation: 1124
off topic it is considered better pratice to do
var testObj = {};
instead of
var testObj = new Object();
Upvotes: 2
Reputation: 25687
You can use for
loop with in
operation.
for(var PropName in testObj) {
var PropValue = testObj[PropName];
....
}
In case, you only want the property with the name started with 'value' only, you can also do this:
for(var PropName in testObj) {
if (!/^value[0-9]$/.match(PropName))
continue;
var PropValue = testObj[PropName];
....
}
OR if the number after the 'value' is always continuous you can just use a basic for loop.
for(var I = 0; I <= LastIndex; I++) {
var PropName = "value" + I;
var PropValue = testObj[PropName];
....
}
Hope this helps.
Upvotes: -1
Reputation: 18775
Use something in the fashion of testObj["volume" + "1"]
;)
The notations object.property
and object["property"]
are (almost) equivalent in javascript.
Upvotes: 0
Reputation: 53940
testObj["volume" + 1]
but you actually want an array here
testObj.volume = [...]
testObj.volume[1] = whatever
Upvotes: 7