Skip to main content
3 of 3
improved formatting
Quill
  • 11.9k
  • 5
  • 40
  • 93

Assign object keys to another object's keys dynamically

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;
    }
}
Leon Gaban
  • 367
  • 2
  • 9