What is the best way to construct an object in Typescript that includes only properties that are not null or undefined?

Below is a sample list of properties:

const firstProperty = this.checkSome(param) ? this.someArray[1] : null;
const secondProperty = this.anotherProperty ? this.anotherProperty.id : null;

I am looking to create an object using these properties:

myObject = {
  firstProperty,
  secondProperty,
};

While everything works as expected, the issue arises when myObject contains properties that are null or undefined. I want the created object to only include properties that have values and exclude any that do not. How can I achieve this in the shortest way possible? Keep in mind that there may be more than two properties, potentially up to a dozen.

Answer №1

It seems like you are discussing an interface with optional properties. Let's delve into that concept.

interface CustomObject {
    propertyOne?: number
    propertyTwo?: string
}

Next, you can define a variable that utilizes this interface but does not include any optional properties:

const customObject: CustomObject = {}

Finally, you can conditionally assign values to these optional properties in the object:

 if (Math.random() > 0.5) customObject.propertyOne = 123
 if (Math.random() > 0.5) customObject.propertyTwo = "a specific value"

Interactive Demo

Answer №2

To eliminate unwanted properties from an object, you have a couple of options. One approach is to iterate through each property and remove it using the delete statement:

Object.keys(myObject).forEach(key => {
  if (obj[key] == null) {
    delete obj[key];
  }
})

Alternatively, you can utilize the reduce method to create a new object with only the desired properties:

const newObj = Object.entries(myObjec).reduce((prev, [key, value]) => {
    if (value != null) {
        prev[key] = value
    }
    return prev
}, {} as typeof myObjec)

Remember to include a type cast when creating the new object to maintain the same data structure.

For more information on this topic, check out these related questions:

  • Javascript - removing undefined fields from an object
  • Remove blank attributes from an Object in Javascript

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

IntelliSense in VSCode is unable to recognize the `exports` property within the package.json file

Currently, I am utilizing a library named sinuous, which contains a submodule known as "sinuous/map". Interestingly, VSCode seems to lack knowledge about the type of 'map' when using import { map } from "sinuous/map", but it recognizes the type ...

What is the proper way to refactor this TypeScript class?

Can you assist me in converting this class into TypeScript and explaining why it's not functioning? class Students { public name: string; public surname: string; public age: number; } constructor(name:string,surname:string,age:number) { ...

Error message: TypeScript is unable to locate module "fs" after installation of @types/node package

Usually, the fix for this issue is to install @types/node. I already have version 10.12.23 of that installed. This error seems unusual and has me quite confused. I currently have 2 other npm modules installed: config (which requires @types/config) and fir ...

Using a Typescript-specific type within a switch case statement

I'm currently working on a function that, when given an enum value, should return a specific type. I am facing an issue where Typescript does not seem to recognize the properties inside switch and if statements. interface X { x: string; } interface ...

What is the best way to retrieve the names of "string" properties from an interface in TypeScript?

Explore Typescript playground I aim to extract the string characteristics from SOME_OBJECT and form them into a union type. Thus, I anticipate STRING_KEYS to signify "title" | "label" interface SOME_OBJECT { title: string, ...

Attempting to populate an array with .map that commences with a designated number in Angular using Typescript

Currently, I am attempting to populate an array with a series of numbers, with the requirement that the array begins with a certain value and ends with another. My attempt at this task involved the code snippet below: pageArray = Array(finalPageValue).fil ...

The module cannot be located: Unable to find '../typings' in '/vercel/path0/pages'

Having trouble deploying my Next.js website through Vercel. It seems to be stuck at this stage. Can someone assist me, please? I've attempted deleting the node_modules folder and package-lock.json, then running npm install again, but unfortunately it ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...

Error encountered during Angular ahead-of-time (AOT) compilation: Internal state issue - Summaries cannot contain members in StaticSymbols

Our team is currently working on implementing ahead of time (AOT) compilation for our Angular 2 project, but we have encountered an error: Error: Internal state: StaticSymbols in summaries can't have members! {"filePath":"C:/Users/bhavy/Documents/p ...

Is there a way to change a typescript callback into a promise?

I am looking to create a method within my class that connects to a MySQL database. I have already written my SQL code and now I want to move away from using callbacks and start implementing promises, as it is more modern. Below is my function with callbac ...

Combining tuples with their corresponding data types

Trying to define a new type: type Union = [1, "one"] | [1, "first"] | [2, "two"] type GetTuple<T, U> = Extract<T, [U, ...unknown[]]>; type ObjectFromUnion<T extends Union[0] = Union[0]> = { number: T, word: ?? } Looking to utiliz ...

What is the best way to iterate through an object and display each item as <li></li> within another <li>?

After retrieving a specific object from an express endpoint and seeing it on the console, I need to figure out how to map it in order to display a jsx that resembles this <li>keys</li> : <li>values</li> For example: Company: DML ...

Checking the next route in Angular 2 when navigating away

Is there a way to trigger an action only on specific NavigationEnd router events, excluding when navigating between child routes or on a particular route? This is a snippet from my app.routing.ts: // other route configurations... { path: 'scrapers/ ...

RTK Query - executing a query upon mounting with lazy loading enabled

Should rerendering be triggered by sending a request on mount? Or is the use of useEffect necessary? (Is lazy mode different from regular queries?) export const Catalog: React.FC<CatalogProps> = ({ object, category }) => { const [getCatalogPro ...

The issue with Rxjs forkJoin not being triggered within an Angular Route Guard

I developed a user permission service that retrieves permissions from the server for a specific user. Additionally, I constructed a route guard that utilizes this service to validate whether the user possesses all the permissions specified in the route. To ...

Issue with linear Graham scan method causing failure when computing convex hull of basic polygon

It is said that the Graham scan algorithm can efficiently find the convex hull of a simple polygon in linear time without requiring the nlogn sorting step since the vertices are already effectively sorted. I have implemented the Graham scan algorithm, and ...

Can you provide guidance on how to specifically specify the type for the generics in this TypeScript function?

I've been diving into TypeScript and experimenting with mapped types to create a function that restricts users from extracting values off an object unless the keys exist. Take a look at the code below: const obj = { a: 1, b: 2, c: 3 } fun ...

Encountering an unsecured WebSocket connection when trying to access the Neo4J endpoint post deployment on Firebase

I have developed an application using Neo4j, but when I try to host the app in Firebase, I encounter the following error: The page at 'https://yourwebsite.com' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint &a ...

JavaScript or Query: Transforming an Object from an Associative Array

Can someone help me out with converting an associative array into an object in JavaScript? I tried searching on Stackoverflow but couldn't find a working example. Here is the example structure: var combinedproducts = [["Testing-1","test-1"],["Testin ...

NodeJS and TypeScript collaborating to manage a limitless AWS S3 bucket in a blank state

Having trouble with my removeObjects function. I'm trying to make it fetch a list of objects from an S3 bucket synchronously and then remove the objects asynchronously. The goal is to repeat this process if the list was truncated until all objects are ...