在具有null字段的typescript对象上循环



尝试在对象上循环。事情是对象a一些字段被定义为null,因为我想绕过firebase不接受未定义的值。目标是:

在型号.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,
};

我可以做到这一点:

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

但我想在这个对象上循环进行,所以我不需要15个If,我的对象仍然可以在Firebase中注册。

我试过foreach,for in,for of,for I。什么都不起作用。我的IDE告诉我页面中并没有这样的属性。

我们可以在Object.entries(page)上迭代,当字符串''长度的值为零或为undefined时,我们将键值更改为null

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

以下是一个工作示例:https://stackblitz.com/edit/how-to-loop-object-keys-and-display-in-table-usin-l7pq7k?file=src%2Fapp%2Fapp.component.ts

您可以按照以下方式进行操作:-

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

您可以像这样循环对象

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

最新更新