Home > Enterprise >  Loop over a typescript object with null fields
Loop over a typescript object with null fields

Time:02-15

Trying to loop on a object. Thing is the object a some fields defined to null, because i want to bypass firebase not accepting undefined values. Here's the object :

In model.ts

export interface Page {
  id: string;
  titre: string;
  pres: string;
  st1: null;
  st2: null;
  st3: null;
  st4: null;
  st5: null;
  pa1: string;
  pa2: null;
  pa3: null;
  pa4: null;
  pa5: null;
  image1: null;
  image2: null;
  image3: null;
  lien: null;
  nomlien: null;
}
In component.ts : 
 page: Page = {
    id: '',
    titre: '',
    pres: '',
    st1: null,
    pa1: '',
    st2: null,
    st3: null,
    st4: null,
    st5: null,
    pa2: null,
    pa3: null,
    pa4: null,
    pa5: null,
    image1: null,
    image2: null,
    image3: null,
    lien: null,
    nomlien: null,
  };

I can make this working :

if (page.st1 === undefined || page.st1 === '') {
      page.st1 = null;
    }

But I would like to do this in a loop on this object, so I don't need 15 Ifs and my object can still be registered in Firebase.

I've tried foreach, for in, for of, for i .Nothing is working. My IDE tells me that there's no such property in page.

CodePudding user response:

We could iterate over Object.entries(page) and where value of string '' length is zero or it is undefined, we change the key value to null.

  setNulls(page: any) {
    for (let [key, value] of Object.entries(page)) {
      if (value === undefined || String(value).length === 0) {
        page[key] = null;
      }
    }
  }

Here is a working example: https://stackblitz.com/edit/how-to-loop-object-keys-and-display-in-table-usin-l7pq7k?file=src/app/app.component.ts

CodePudding user response:

You can do it like below :-

if (page) {
  Object.keys(page).forEach((key) => {
    if (page[key] === undefined || page[key] === '') {
       page[key] = null;
    }
  })
}

CodePudding user response:

You can loop object like this

for (const key of Object.keys(this.page)) {
    if (this.page[key] === undefined || this.page[key] === ''){
        (<any>this.page)[key] = null;      
    }
}
  • Related