0
\$\begingroup\$

My view object:

{
    description: "2tik 2tags"
    id: 100
    portfolio: "TSLA"
    term_id_1: 260751
    term_id_2: 285493
    term_id_3: null
    ticker_1: "GOOG"
    ticker_2: "TSLA"
    ticker_3: ""
    timespan: "ld"
    top: ""
}

I need to grab the term_ids and stick them into a new array, but only if they are not null.

What I'm currently using:

function reSelectTags(view) {
    console.log('view',view);
    // Seperate term_ids:
    var term_ids = [];

    if (view.term_id_1 != null) {
        term_ids.push(view.term_id_1);
    }

    if (view.term_id_2 != null) {
        term_ids.push(view.term_id_2);
    }

    if (view.term_id_3 != null) {
        term_ids.push(view.term_id_3);
    }

    console.log('term_ids',term_ids);
}

This gets the job done, but I'm wondering if there is a better, cleaner way, perhaps on 1 or 2 lines that could accomplish this as well.

\$\endgroup\$
2
\$\begingroup\$

Since the property names are sequential, you can just put it into a for loop:

function reSelectTags(view) {
    var val, term_ids = [];
    for (var i = 1; i <= 3; i++) {
        val = view["term_id_" + i];
        if (val != null) {
            term_ids.push(val);
        }
    }
    console.log(term_ids);
}

You can also just put repeated code into a local function:

function reSelectTags(view) {
    var term_ids = [];

    function pushVal(name) {
        if (view[name] != null) {
            term_ids.push(view[name]);
        }
    }
    pushVal("term_id_1");
    pushVal("term_id_2");
    pushVal("term_id_3");
    console.log(term_ids);
}
\$\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.