Refactor forEach loop