fix the each function to support nesting