How to get the name of a field? I'm on hook_form_alter for the config edit form. The code runs for all fields, but it's critical that the code figures out the name of the field it is on. 

When I load the formobject, I can see the field_name perfectly when I print_r the array. But I can't figure out how to pull it out. Something like $name=$field['field_name']

The field name is 'field_plan_purpose' I need to get that in a variable in the code.

My code minus all of things I've tried:

$field = $form_state-&gt;getFormObject()-&gt;getEntity();
print '&lt;pre&gt;';
print_r($field);
print '&lt;/pre&gt;';


Here is the top part of the array that gets printed:

Drupal\field\Entity\FieldConfig Object
(
    [deleted:protected] =&gt; 
    [fieldStorage:protected] =&gt; Drupal\field\Entity\FieldStorageConfig Object
        (
            [id:protected] =&gt; node.field_plan_purpose
            [field_name:protected] =&gt; field_plan_purpose &lt;--- HOW DO I GET THIS
            [entity_type:protected] =&gt; node
            [type:protected] =&gt; text_long
            [module:protected] =&gt; text
            [settings:protected] =&gt; Array
                (
                )

            [cardinality:protected] =&gt; 1
            [translatable:protected] =&gt; 1
            [locked:protected] =&gt; 
            [persist_with_no_fields:protected] =&gt; 
            [custom_storage] =&gt; 
            [indexes:protected] =&gt; Array
                (
                )

            [deleted:protected] =&gt; 
            [schema:protected] =&gt; 
            [propertyDefinitions:protected] =&gt; Array
                (...


As you can see, 'field_name' is in there. Does anyone know how I can pull that out and reference it directly?

A few things I've tried:

    // print_r($field-&gt;getEntityKey('#field_name'));
    // getEntityType()-&gt;getKey('field_name')
    // $field['field_name']  $field['field_name:protected']
    // $field['id']
    // $field-&gt;getKey('field_name')
    // $field-&gt;definition['field_name'];
    // print_r($field-&gt;definition);


EDITED ******* SOLUTION

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&amp;$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

   $field = $form_state-&gt;getFormObject()-&gt;getEntity();
   $field_name = $field-&gt;getName();
   print $field_name;

}
FieldConfigBase has a method named getName(). That will retrieve the field name:

public function getName() {
  return $this-&gt;field_name;
}