The forEach is undefined in a Javascript Class Method

268 Views Asked by At

I are have a problem into my code. After many attempts in search for solutions I decided to get help from the stackoverflow community

I have created a Javascript Class for get registered members list. This members register is localized in to a Json file which system have access.

I'm trying to use an array data filter through forEach. But the method named: "Of(ChurchName)" don't read any foreach method into it. When I using into Of(), returns undefined.

Initially I used 'return' response in the method "createMemberList()", responsible to create the full array. This method it's working normally. But, using 'return' in a variable with ForEach method not work. Then, because this aparent error, I has used the 'this' operator instead of 'return'. But even so, as can you see in code, i can't use the forEach method at "createMemberList()". Does anyone has any idea?

Details: I aredy used that site tips: https://www.techiedelight.com/copy-elements-array-into-another-array-javascript/

   const $INIT = {
        GetMembers: class{
            #listaOrdenadaItens;
            #listaMembros;
            #MemberListOfChurch;
            membersList;
            #linkGFile="LinkToJsonFileHere";
            /*Returns:
   {
         "range": "Membros!B5:AB234",
         "majorDimension": "ROWS",
         "values": [
        
            [ "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              ""]
         ]
    }

 */
            constructor(ListFromGD){
                if(typeof ListFromGD!=="undefined"&&ListFromGD!==null){
                    this.#linkGFile=ListFromGD;
                }
                this.#createMemberList();
            }
            /*Members List*/
            Of(ChurchName){
                /**Filters member data according congregation
                 * Usage: new $INIT.GetMembers().Of("ChurchName")
                 */
                this.#MemberListOfChurch=[];;
                this.ChurchName=ChurchName;
                    
                this.membersList.forEach((item, count) => {
                 console.log("Why this code don't appears in console?");
                    if (/^[a-zA-Z_À-Úà-ú\s]{2,50}$/.test(ChurchName)==true && ChurchName.toLocaleLowerCase() == item.congregacao.toLocaleLowerCase()) {
                        
                        this.#MemberListOfChurch[count] = item;
                    }else{
                        console.log("Trys to check anyone error");
                    }
    
                }); 
                 
                return this.#MemberListOfChurch;
            }
            #getListaOrdenada (){
               return [
                   /**Personal Informations */
                   "Nome Completo",
                   "Sexo",
                   "CPF",
                   "Data de Nascimento",
                   "RG",
                   "Orgão Emissor",
                   "UF_RG",
                   "Data de Expedição",
                   "Estado Civil",
                   "CONJUGE",
                   "Naturalidade",
                   "UF_NAT",
                   "NOME_PAI",
                   "NOME_MAE",
    
                   /**Schooling and ecclesiastical data */
                   "GRAU_INSTRUCAO",
                   "PROFISSAO",
                   "FUNCAO_ECLESIASTICA",
                   "LOCAL",
                   "UF_BATISMO",
    
                   /**Address informations */
                   "Endereco",
                   "cep",
                   "bairro",
                   "cidade",
                   "uf",
                   "congregacao",
                   "contact_number",
                   "whatsapp_number"
    
               ]
            }
            #createMemberList(){
                var listaOrdenada = this.#getListaOrdenada();
    
                /**Create an array */
                var NewListMember = [];
                
                var DadosMembros={};
                /**
                 * Gets registered members list at system!
                 */
                this.#getJSON(this.#linkGFile).then(response=>{
                    response.values.forEach((item, i)=>{
                        /**Examina membro por membro aqui */
                        if(item[0]===undefined)return;

                        /**Creates a name for array of values: Ex: {"Complete Name" : "Leonardo Lima de Sousa"} */
                        listaOrdenada.forEach((ItemName,N)=>{
                            if(ItemName===undefined) return;
                            DadosMembros[ItemName]=item[N];
                        });
                        
            
                         NewListMember[i] = DadosMembros;
                         DadosMembros={};
                    });
                })
    
                this.membersList=NewListMember;
            }
    
            #getJSON=async t=>{const r=await fetch(t);if(!r.ok)throw new Error(r.statusText);return r.json()};
            
    
        }
    }

If I run this code of this function directly in the Chrome Console, it's works. But in this Class Method, returns undefined

3

There are 3 best solutions below

0
On BEST ANSWER

DEFINITIVE SOLUTION

where were problem? What's solution? The #createMemberList() generate an array with more than 220 rows. Then, it's necessary wait a while for Of() method to process everything. For it, it's must to use setTimeout() function in the method, like this:

setTimeout(()=>{
    console.log(JSON.stringify(this.membersList))
},3000)

The code will to stay like this:

     const $INIT = {
            GetMembers: class{
                #listaOrdenadaItens;
                #listaMembros;
                #MemberListOfChurch;
                membersList;
    #linkGFile="https://cdn.jsdelivr.net/gh/OficialLeonardoLima/cdn@main/json_test.json";
         
                constructor(ListFromGD){
                    if(typeof ListFromGD!=="undefined"&&ListFromGD!==null){
                        this.#linkGFile=ListFromGD;
                    }
                    this.#createMemberList();
                  setTimeout(()=>{
                    console.log(JSON.stringify(this.membersList))
                  },3000)
                  
                  document.querySelector("#console").text=JSON.stringify(this.membersList)
                }
                /*Members List*/
                Of(ChurchName){
                    /**Filters member data according congregation
                     * Usage: new $INIT.GetMembers().Of("ChurchName")
                     */
                    this.#MemberListOfChurch=[];;
                    this.ChurchName=ChurchName;
                    
setTimeout(()=>{   
this.membersList.forEach((item, count) => {
                 console.log("Why this code don't appears in console?");
                    if (/^[a-zA-Z_À-Úà-ú\s]{2,50}$/.test(ChurchName)==true && ChurchName.toLocaleLowerCase() == item.congregacao.toLocaleLowerCase()) {
                        
                        this.#MemberListOfChurch[count] = item;
                    }else{
                        console.log("Trys to check anyone error");
                    }
    
                }); 
                                         },3000);
                     
                    return this.#MemberListOfChurch;
                }
                #getListaOrdenada (){
                   return [
                       /**Personal Informations */
                       "Nome Completo",
                       "Sexo",
                       "CPF",
                       "Data de Nascimento",
                       "RG",
                       "Orgão Emissor",
                       "UF_RG",
                       "Data de Expedição",
                       "Estado Civil",
                       "CONJUGE",
                       "Naturalidade",
                       "UF_NAT",
                       "NOME_PAI",
                       "NOME_MAE",
        
                       /**Schooling and ecclesiastical data */
                       "GRAU_INSTRUCAO",
                       "PROFISSAO",
                       "FUNCAO_ECLESIASTICA",
                       "LOCAL",
                       "UF_BATISMO",
        
                       /**Address informations */
                       "Endereco",
                       "cep",
                       "bairro",
                       "cidade",
                       "uf",
                       "congregacao",
                       "contact_number",
                       "whatsapp_number"
        
                   ]
                }
                #createMemberList(){
                    var listaOrdenada = this.#getListaOrdenada();
        
                    /**Create an array */
                    var NewListMember = [];
                    
                    var DadosMembros={};
                    /**
                     * Gets registered members list at system!
                     */
                    this.#getJSON(this.#linkGFile).then(response=>{
                        response.values.forEach((item, i)=>{
                            /**Examina membro por membro aqui */
                            if(item[0]===undefined)return;
    
                            /**Creates a name for array of values: Ex: {"Complete Name" : "Leonardo Lima de Sousa"} */
                            listaOrdenada.forEach((ItemName,N)=>{
                                if(ItemName===undefined) return;
                                DadosMembros[ItemName]=item[N];
                            });
                            
                
                             NewListMember[i] = DadosMembros;
                             DadosMembros={};
                        });
                    })
        
                    this.membersList=NewListMember;
                }
        
                #getJSON=async t=>{const r=await fetch(t);if(!r.ok)throw new Error(r.statusText);return r.json()};
                
        
            }
        }
    
4
On

const newArr = [...arr1, ...arr2] will copy all the elements from arr1 and arr2 to newArr. You don't need to use foreach.

2
On

TEMPORARY SOLUTION

A temporary solution for this problem is copy CreateMemberList() content to Of() Method. Thereafter, It's necessary create a new Array named NewListMember[] and apply congregations data via objects to it where congregation name is equal ChurchName param

The Of() Method will be staying this:

Of(ChurchName){
            /**Filters member data according congregation
                 * Usage: new $INIT.GetMembers().Of("ChurchName")
                 */
            
            var 
                listaOrdenada   =   this.#getListaOrdenada(),
                NewListMember   =   [], 
                newArray        =   [],
                DadosMembros    =   {};
            /**
             * Gets all registered members data by Json array.
             */
            this.#getJSON(this.#linkGFile).then(response=>{
                //Creates a counter variable
                var newI=0;
                
                response.values.forEach((item, i)=>{
                    /**examines member by member here */
                    if(item[0]===undefined)return;
                    
                    /**Creates a property name for this array value: }
                      *Ex: {"Nome completo" : "Leonardo Lima de Sousa"} 
                      *     "Complete Name"
                    */
                    listaOrdenada.forEach((ItemName,N)=>{
                        if(ItemName===undefined) return;
                        DadosMembros[ItemName]=item[N];
                    });

                    //Gets current congregation name and set all letters to lowerCase()
                    var ThisCongregation        = DadosMembros.congregacao;ThisCongregation=ThisCongregation.toLowerCase();
                    
                    //Gets congregation name in to param: ChurchName and set all letters to lowerCase()
                    var CongregationIndicate    = ChurchName.toLowerCase();

                    //Gets Congregation where Congregation name is equal Param ChurchName
                    ////Then, creates a new size for array NewListMember with newI counter
                    if(ThisCongregation!==undefined&&ThisCongregation!==CongregationIndicate)return;
                     NewListMember[newI] = DadosMembros;
                     ++newI;
                     DadosMembros={};
                });
            });
            return NewListMember
        }