根据Javascript / TypeScript对象的非null属性创建数组 [英] Create an array from non null properties of Javascript/typescript object
问题描述
我有一个打字稿POJO,如下所示:
I have a typescript POJO as follows
export interface Items {
firstName?: String;
lastname?: String;
Address?: String;
phoneNumber?: number;
city?: String;
state?: String;
zipcode?: number;
accountId?: number;
status?: String;
approvalStatus?: String;
txId?: number;
rxId?: number;
txBankname?: String;
rxBankName?: String;
txCcy?: String;
rxCcy?: String;
txCcyAmt?:number;
rxCcyAmt?:number;
txDate?:date;
rxDate?:date;
}
在我的html文件中,我有一个表单,其中包含POJO上方的所有字段。当用户选择一个字段时,pojo将使用输入的文本填充。
In my html file, I have a form with all the fields from above POJO. When a user selects a field, the pojo gets populated with the text entered.
不过,用户可以选择将许多字段保留为空,并且它们在对象中的属性为null。
However the user can choose to remain many fields empty and their properties in the object would be null.
在单击提交按钮时,当我检查POJO时,如下所示。
So on submit button click, when I check the POJO, it is as in the below screeshot.
我只想填充另一个数组填充的值(不是null值属性)。
I want to populate another array with only the populated values ( not the null value properties ) .
this.anotherArray = [ {name:firstName, value:"Andy"},{name:lastName, value:"Smith"}]
我需要将其用于ngFor列表以显示有角度的材料芯片
I need to use it for an ngFor List to display angular material chip
我们如何以非常优化的方式进行处理。
How do we do it in a very optimized way.
编辑:我的问题是关于检查对象中的空属性,而重复的问题引用是对数组的引用。甚至答案也有不同的方法。解决这个问题的方法是使用Object.entries,而重复引用使用的是map和Object.keys
edit: My question is regarding checking null properties in object and the duplicate question reference is to an array. Even the answers have different approaches. The Approach to my question is using Object.entries while the duplicate reference has an approach of using map and Object.keys
推荐答案
您可以使用 Object.entries ()
以获得名称/值对,然后将它们映射到对象:
You can use Object.entries()
to get name-value pairs, then map them to objects:
Object.entries(obj)
.filter(([name, value]) => value !== null)
.map(([name, value]) => ({name, value}));
这篇关于根据Javascript / TypeScript对象的非null属性创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!