返回typescript中包含选定键值对的新对象



我有一个person类型的大对象,如果存在,我想只显示几个值(可能会增长)。键值的一行div,如果它们在某些数组中指定,例如。hasProperty

我的想法是获得一个Person对象,映射它与数组hasProperty:string[]=['dateOfBirth','address']到一个新对象然后在前端我可以输入

<div for=newObjectValue in newObject>
<span>key somehow?</span>
<span>{{newObjectValue.value`}}</span>
</div>

这有可能做得更好吗?我知道上面的想法很糟糕,但这是目前为止我能想到的最好的办法了

你可以这样做

app.component.ts

person = {
firstName: 'John',
lastName: 'John'
age: 20,
nationality: Canadian,
......
};
personObjectKeys = Object.keys(person);

在你的模板中,你可以在一个循环中这样做app.component.html

<div class="record-row" *ngFor="let personKey of personObjectKeys">
<ng-container *ngIf="person[personKey]">
<span>{{personKey}}</span>
<span>{{person[personKey]}}</span>
</ng-container>
</div>

最新更新