Search code examples
javascriptjsondynamic-arrays

What is a better way to access properties of JSON object if they have names like option1, option2


The configObj has many properties like { 'name':'test', 'option1': 'test', 'option3': 'test', 'option2': 'test', 'option4': 'test', 'other1':'blah', 'other2':'blah2' }

I was wondering if there was a way to do something like this:

like convert this

optionArray[i++] = configObj.option1; 

to this

optionArray[i++] = configObj.option + i;

FULL CODE :

var optionArray = new Array();
var i = 0;
if (configObj.option1 != "") {
    optionArray[i++] = configObj.option1;
}
if (configObj.option2 != "") {
    optionArray[i++] = configObj.option2;
}
if (configObj.option3 != "") {
    optionArray[i++] = configObj.option3;
}
if (configObj.option4 != "") {
    optionArray[i++] = configObj.option4;
}

Solution

  • Try with this code:

    var optionArray = new Array();
    for (i = 1; i <= 4; ++i) {
        var option = configObj["option" + i] ;
        if (option != "") {
            optionArray.push(option);
        }
    }