最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Create an array from non null properties of Javascripttypescript object - Stack Overflow

programmeradmin8浏览0评论

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

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

Share Improve this question edited Jul 13, 2018 at 20:37 prabhat gundepalli asked Jul 13, 2018 at 15:19 prabhat gundepalliprabhat gundepalli 9673 gold badges17 silver badges39 bronze badges 1
  • 4 Possible duplicate of Javascript filter null object properties – Brandon Taylor Commented Jul 13, 2018 at 15:21
Add a comment  | 

3 Answers 3

Reset to default 13

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

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

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

发布评论

评论列表(0)

  1. 暂无评论