Assign values to dynamic structure

Czarinaaaaa29 picture Czarinaaaaa29 · Dec 13, 2017 · Viewed 9.3k times · Source

Need idea on the below codes, on how to simplify. Codes below works good but is there a way I could enhance or shorten the codes making it dynamic?

    TYPES: BEGIN OF lty_dates,
             yesterday TYPE string,
             today     TYPE string,
             tomorrow  TYPE string,
           END OF lty_dates.

    DATA: it_table TYPE TABLE OF lty_dates.

    DO 3 TIMES.
      CASE lv_count.
        WHEN 1.
          it_table[ 1 ]-zyesterday = 'Result Yesterday'.
          it_table[ 2 ]-zyesterday = 'Result Yesterday'.
          it_table[ 3 ]-zyesterday = 'Result Yesterday'.

        WHEN 2.
          it_table[ 1 ]-ztoday = 'Result Today'.
          it_table[ 2 ]-ztoday = 'Result today'.
          it_table[ 3 ]-ztoday = 'Result Today'.

        WHEN 3.
          it_table[ 1 ]-ztommorrow = 'Result Tomorrow'.
          it_table[ 2 ]-ztommorrow = 'Result Tomorrow'.
          it_table[ 3 ]-ztommorrow = 'Result Tomorrow'.
      ENDCASE.

      lv_count = lv_count + 1.

    ENDDO.

My idea is something like the below pseudocodes. I would not want to perform CASE multiple times specially instances if fields for it_table would reach 100 (fields).

   DO 3 TIMES.
      ASSIGN 'ZTODAY' TO <dynamic_fieldname>.
      it_table[ 1 ]-<dynamic_fieldname> = <dynamic_result>.
      it_table[ 2 ]-<dynamic_fieldname> = <dynamic_result>.
      it_table[ 3 ]-<dynamic_fieldname> = <dynamic_result>.
    ENDDO.

Please help or light me up on this.

Answer

Michael Meyer picture Michael Meyer · Dec 14, 2017

You could use the command ASSIGN COMPONENT compname OF STRUCTURE structure TO <field_symbol>.

TYPES: BEGIN OF lty_dates,
         yesterday TYPE string,
         today     TYPE string,
         tomorrow  TYPE string,
       END OF lty_dates.

TYPES: BEGIN OF lty_result ,
         fieldname TYPE fieldname,
         result    TYPE string,
       END OF lty_result .

FIELD-SYMBOLS <data> TYPE any .

DATA: lt_table  TYPE TABLE OF lty_dates,
      lt_result TYPE TABLE OF lty_result.

lt_result = VALUE #( ( fieldname = 'yesterday'
                       result    = 'Result Yesterday' )
                     ( fieldname = 'today'
                       result    = 'Result Today' )
                     ( fieldname = 'tomorrow'
                       result    = 'Result Tomorrow' ) ).

lt_table = VALUE #( (  ) (  ) (  ) ). " 3 empty lines

LOOP AT lt_table ASSIGNING FIELD-SYMBOL(<table>) .
  LOOP AT lt_result ASSIGNING FIELD-SYMBOL(<result>) .
    ASSIGN COMPONENT <result>-fieldname OF STRUCTURE <table> TO <data> .
    <data> = <result>-result.
  ENDLOOP .
ENDLOOP .