Skip to main content
1 of 3
Leon Gaban
  • 367
  • 2
  • 9

How to optimize this code into a loop?

I have an Array viewObject.terms this array can contain up to 3 items. I need to iterate through the array and save the values into a data object.

ie:

data.term_id_1 = viewObject.terms[0].term_id
data.ticker_1  = viewObject.terms[0].its_ticker

This is what I first tried, but I get the error can't set '0' of undefined:

enter image description here

for (var i=0; i<viewObject.terms.length; i++) {
    data.term_id_[i+1] = viewObject.terms[i].term_id;
    data.ticker_[i+1]  = viewObject.terms[i].its_ticker;
}

So for the moment I'm just using a switch case to handle this currently (albeit in a super ugly way):

if (viewObject.terms.length > 0) {
    switch(viewObject.terms.length) {
        case 1:
            data.term_id_1 = viewObject.terms[0].term_id;
            data.ticker_1  = viewObject.terms[0].its_ticker;
            break;
        case 2:
            data.term_id_1 = viewObject.terms[0].term_id;
            data.ticker_1  = viewObject.terms[0].its_ticker;
            data.term_id_2 = viewObject.terms[1].term_id;
            data.ticker_2  = viewObject.terms[1].its_ticker;
            break;
        case 3:
            data.term_id_1 = viewObject.terms[0].term_id;
            data.ticker_1  = viewObject.terms[0].its_ticker;
            data.term_id_2 = viewObject.terms[1].term_id;
            data.ticker_2  = viewObject.terms[1].its_ticker;
            data.term_id_3 = viewObject.terms[2].term_id;
            data.ticker_3  = viewObject.terms[2].its_ticker;
            break;
    }
}
Leon Gaban
  • 367
  • 2
  • 9