JavaScript: refactoring, avoiding array.push()

arrays, javascript

Solution

You could move the `is*` properties to a sub-object so as to isolate them, and loop over the sub-object's properties

item.is={A:'aClass', C:'cClass'};
...
arrayofElements: function(item) {
    var result = [];
    for (p in item.is) {
        result.push(new Div(item.is[p], labels[p]));
    }
    return result;
},

The values in `item.is` could be the classes (as shown), or the values in `item.is` could be objects with a `class` property, or you could use the property name `p` as an index in another object to get the classes. Which depends largely on what the `item`s represent and what the element classes are most closely associated with.

Problem

I've got a function in an object like this: ``` arrayofElements: function(item) { var result = []; if (item.isA) { result.push(new Div('aClass', labels['A'])); } if (item.isC) { result.push(new Div('cClass', labels['C'])); } if (item.isD) { result.push(new Div('dClass', labels['D'])); } return result; }, ``` How can this be refactored? I dislike having to push() each item conditionally.

Original source