Generate an array by filtering out null properties from a Javascript/Typescript object

I have a TypeScript plain old JavaScript object (POJO) structured as shown below:

  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 that includes all the fields from the above POJO. When a user selects a field, the POJO is updated with the entered text.

However, users have the option to leave many fields empty, resulting in corresponding properties in the object being set to null.

Upon clicking the submit button, when I examine the POJO, it appears as shown in the screenshot below:

https://i.sstatic.net/N8lTI.jpg

I want to create another array that only contains the populated values (excluding the null properties).

  this.anotherArray = [ {name: firstName, value: "Andy"}, {name: lastName, value: "Smith"}]

I intend to utilize this array for an ngFor list to display Angular Material chips.

How can I achieve this in a highly optimized manner?

edit: My question pertains to checking null properties in an object, whereas the referenced duplicate question relates to an array. The solutions presented also differ, with my approach involving the use of Object.entries, as opposed to the duplicate reference which utilizes map and Object.keys.

Answer №1

If you want to extract name-value pairs from an object in JavaScript, you can utilize the Object.entries() method and then transform them into separate objects using the map function:

Object.entries(obj)
    .filter(([name, value]) => value !== null)
    .map(([name, value]) => ({name, value}));

Answer №2

You can easily utilize Object.entries() along with Array.reduce()

var items = {
  "title":"example",
  "quantity" : 3,
  "price" : null,
  "available" : true
};

var output = Object.entries(items).reduce((accumulator,[key,value])=>{
  if(value)
    accumulator.push({title : key, content : value});
  return accumulator;
},[]);

console.log(output);

Result:

[
  {
    "title": "title",
    "content": "example"
  },
  {
    "title": "available",
    "content": true
  }
]

Answer №3

Here is a potential solution:

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)

Applying the same method with local mutation

Using local mutation with Array#reduce accumulator can optimize the process.

By pre-allocating an array with N empty slots (where N is the total number of keys in the input object), the array's length does not need to be adjusted during the reduction operation. After reducing the object's entries, we eliminate 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)

For performance comparison, check out JSPerf test filter+map vs reduce+filter

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error TS2345: The argument provided, which is of type 'Promise<ReadonlyArray<Object>>', cannot be assigned to a parameter that must be of type 'T | PromiseLike<T> | undefined'

My goal is to return the ReadonlyArray<> in my promise so that I can send it back to the original method that called 'dispatchToThisProcess'. This abstraction allows for potential future updates to multiple processes. Below is the code snip ...

Dealing with errors in node.js

Node.js asynchronous functions typically have a callback, with some like fs.writeFile passing an err argument. fs.writeFile('message.txt', 'Hello Node', function (err) { if (err) throw err; console.log('It\'s saved!& ...

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

Downloading a PDF in a Next.js application

How can I add a button or link that will instantly download my PDF portfolio when clicked? I am currently working on my resume section and would like to provide users with the option to easily download my CV. Is there a way to do this, and if so, how can ...

What is the correct way to utilize default props in a Typescript-powered React component?

Recently diving into React, I find myself working on a basic child-component. My goal is to establish default props so that if no specific prop is provided when the component is invoked, it automatically resorts to the preset defaults. Here's what I&a ...

javascript The event handler is not functioning properly for the dynamically loaded AJAX content

I am facing an issue with adding a JavaScript event listener to a dynamically loaded div via AJAX. Below is my code snippet: var QuantityMiniCart = function() { var infor = document.querySelectorAll( '.mini-cart-product-infor' ); if ( ...

Is There a Quicker Alternative to Eval for Generating Deep Clones?

I am looking to create deep clones of a very large object called veryBigObject. To initialize veryBigObject, it first needs to be initialized using the initVeryBigObject function. Here is how this process looks: initVeryBigObject = function(){ veryBig ...

Transitioning an NX environment to integrate ESM

My NX-based monorepo is quite extensive, consisting of half a dozen apps, frontend, backend, and dozens of libs. Currently, everything is set up to use commonjs module types, as that's what the NX generators have always produced. However, many librar ...

Is there a specific point in which we can directly pass a value to the `state` in Redux?

Is it safe to directly pass the value to the state in a redux reducer like this? export default (state = [], action) => { switch (action.type) { case 'FETCH_USER': return [...state, action.payload]; default: return state; ...

Is it possible to use square brackets in conjunction with the "this" keyword to access a class property using an expression?

export class AppComponent implements OnInit { userSubmitted = false; accountSubmitted = false; userForm!: FormGroup; ngOnInit(): void {} onSubmit(type: string): void { this[type + 'Submitted'] = true; if(this[type + 'For ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

Discovering the optimal method for modifying the state of an object within Object-Oriented Programming using Typescript

I have implemented Object Oriented Programming in my project and I am exploring ways to effectively change the state of an object while ensuring its integrity. Although I have created a code snippet for this purpose, I am curious if there are more optimize ...

Eliminate incorrect or invalid state when resetting a dropdown in an Angular ng-select component

I have integrated the ng-select plugin into my Angular project for handling dropdowns. One specific requirement I have is to reset the second dropdown when the first dropdown is changed. Below is a snippet of the code: <ng-select [items]="branchMo ...

What is the best way to modify a node_module file consisting of only a few exported variables, which is heavily utilized in the entire module? (with demonstration)

I have integrated a node module with the file structure displayed below. Inside the file node_core_ctx.js, I found this code snippet: const EventEmitter = require('events'); let sessions = new Map(); let publishers = new Map(); let idlePlayers ...

Vue users are experiencing issues with the functionality of the Chart js plugin annotation

I've been attempting to include a horizontal line in my Chart.js using the annotations plugin, but it's not cooperating. My Chart.js version is 2.9.4, so I had to install it with the command: npm install [email protected] --save After inst ...

What is the best method for choosing a document from a Firebase based on its creation time?

Currently delving into Firebase as part of my project, struggling with setting queries in the Database. I've provided a breakdown of my Firebase database structure below: Looking to retrieve the most recently created document from the 'subscrip ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

Having trouble showing JSON data with Ionic 2 and Xcode?

Extracting JSON data from a JSON file in my project and viewing it using "ionic serve" on my Mac has been successful. However, I am facing an issue after building for IOS in XCode. I import the generated project into XCode as usual, but the JSON data is no ...

`Carousel nested within tabbed interface`

I am currently facing an issue with my website's tabs and carousels. I have 4 tabs, each containing a carousel, but only the carousel in the first tab seems to be working properly. When I activate the second tab, all the carousel divs collapse. For r ...

Unravel the encoded string to enable JSON parsing

Here is an example of my JSON string structure [{&#034;id&#034;:0,&#034;nextCallMills&#034;:0,&#034;delay&#034;:0,&#034;start&#034;:&#034;... I am facing an issue with JSON.parseString() Even after trying unescape() a ...