1
\$\begingroup\$

I have an array called viewObject.terms. This array can contain up to 3 items, I need to iterate through this 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: Cannot set property '0' of undefined

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;
}

TypeError


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;
    }
}
\$\endgroup\$
  • \$\begingroup\$ as phrased, this seems more akin to a stackoverflow type question, because you're receiving an error (exception)... but it's likely answered already, and so it'll just be flagged as a duplicate. \$\endgroup\$ – Brett Caswell Oct 14 '15 at 0:48
3
\$\begingroup\$

Another solution to the problem could be expressed using Array.prototype.forEach(), as the following:

viewObject.terms.forEach(function(term, index){
    data['term_id_' + (index + 1)] = term.term_id;
    data['ticker_'  + (index + 1)] = term.its_ticker;
});
\$\endgroup\$
0
\$\begingroup\$

Just figured this out! Hope my answer helps someone else:

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;
}

This is how you dynamically name and iterate keys inside of an object

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.