Create an array from non null properties of Javascript/typescript object

末鹿安然 提交于 2020-06-16 04:57:06

问题


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;
     }

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.

However the user can choose to remain many fields empty and their properties in the object would be null.

So on submit button click, when I check the POJO, it is as in the below screeshot.

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"}]

I need to use it for an ngFor List to display angular material chip

How do we do it in a very optimized way.

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


回答1:


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}));



回答2:


You can simply use Object.entries() and Array.reduce()

var fields = {
  "name":"andy",
  "age" : null,
  "email" : null,
  "status" : true
};

var result = Object.entries(fields).reduce((a,[key,val])=>{
  if(val)
    a.push({name : key, value : val});
  return a;
},[]);

console.log(result);

Output:

[
  {
    "name": "name",
    "value": "andy"
  },
  {
    "name": "status",
    "value": true
  }
]



回答3:


One possible approach:

const obj = { a: 1, b: null, c: 2, d: null }

const output = Object.entries (obj)
                     .reduce ((a, [k, v]) => v !== null ? [...a, [k, v]] : a, [])
      
console.log(output)

Same approach with local mutation

Here's the same approach using local mutation of Array#reduce accmulator, which is more optimal.

Since Array#reduce receives an already allocated array with N empty slots (where N is the total number of keys in the input object), the array never requires an internal operation to increase its length. Once the object's entries are reduced, we filter out undefined items (those that were null):

const obj = {
  a: 1,
  b: null,
  c: 2,
  d: null
}

const keyCount = Object.keys(obj).length

const output = Object.entries(obj)
  .reduce((a, kvp, i) => {
    if (kvp[1] !== null) a[i] = kvp
    return a
  }, Array(keyCount))
  .filter(kvp => kvp)

console.log(output)

JSPerf perf test filter+map vs reduce+filter



来源:https://stackoverflow.com/questions/51328310/create-an-array-from-non-null-properties-of-javascript-typescript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!