Javascript refactor for iterating