3

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!

4 Answers 4

7
   testObj["volume" + 1]

but you actually want an array here

   testObj.volume = [...]
   testObj.volume[1] = whatever
Sign up to request clarification or add additional context in comments.

Comments

2

off topic it is considered better pratice to do

var testObj = {};

instead of

var testObj = new Object();

1 Comment

sorry about that, am new to stackoverflow
0

Use something in the fashion of testObj["volume" + "1"] ;)

The notations object.property and object["property"] are (almost) equivalent in javascript.

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.