Leon Gaban Leon Gaban - 5 months ago 9
Javascript Question

How to simplify / streamline this code? (Object check into function call)

First this is what my

urlObject
looks like:

{
term_id_1: "2155"
term_id_2: "2894"
ticker_1: "SPY"
ticker_2: "SPY"
}


I can have up to 3 terms and tickers so like:

ticker_1
,
ticker_2
,
ticker_3


With their matching tags:

term_id_1
,
term_id_2
,
term_id_3


Here is my current function that checks if the ticker and tag combinations exists then calls another function:

function rebuildContainer(urlObject) {
console.log('urlObject',urlObject);

if (urlObject.ticker_1 && urlObject.term_id_1) {
var tickerObj = {};
tickerObj.ticker = urlObject.ticker_1;
var tagObj = {};
tagObj.term_id = urlObject.term_id_1;
saveTickerTags(tickerObj, tagObj);
}

if (urlObject.ticker_2 && urlObject.term_id_2) {
var tickerObj = {};
tickerObj.ticker = urlObject.ticker_2;
var tagObj = {};
tagObj.term_id = urlObject.term_id_2;
saveTickerTags(tickerObj, tagObj);
}

if (urlObject.ticker_3 && urlObject.term_id_3) {
var tickerObj = {};
tickerObj.ticker = urlObject.ticker_3;
var tagObj = {};
tagObj.term_id = urlObject.term_id_3;
saveTickerTags(tickerObj, tagObj);
}
}


This feels like it could be easily simplified, how would you do it?

Answer

Haven't really tested much, but this should work so that you won't have to hardcode the id...

function rebuildContainer(urlObject) {
    // get the keys that contain the 'ticker' text
    Object.keys(urlObject).filter(function (k) {
        return k.indexOf('ticker') > -1;
    }).forEach(function (k) {
        // get the number at the end and look it up on the urlObject
        var termId = urlObject['term_id_' + k.match(/\d+$/)[0]];
        // if it is defined, save the object
        if(termId !== undefined) {
            var tickerObj = {};
            var tagObj = {};
            tickerObj.ticker = urlObject[k];
            tagObj.term_id = termId;
            saveTickerTags(tickerObj, tagObj);
        }
    });
}