Is it possible to convert any object field that holds an empty string to null without having to iterate through

We have an object with values assigned but some of them are empty. Here is the object:

{
    value1: 'bacon',
    value2: '',
    value3: 'lard',
    value4: '',
    value5: 'cheese',
};

Can we transform this object without using iteration to have the following structure?:

{
    value1: 'bacon',
    value2: null,
    value3: 'lard',
    value4: null,
    value5: 'cheese',
};

Answer №1

Iteration is necessary in order to achieve this task. From the perspective of an external function, your object is regarded as a random collection of key-value pairs.

One efficient way to accomplish this is by using a library such as lodash and its mapValues function:

_.mapValues(myObj, val => val === '' ? null : val)

Alternatively, you can achieve this without relying on an external library (this example modifies the original object):

Object.keys(myObj).forEach(key => myObj[key] = myObj[key] === '' ? null : myObj[key])

Another approach to partially address your requirement is by using a Proxy object. This method offers a lazy solution where the object values are not actively changed, but will return null when an empty string is encountered:

const proxyObj = new Proxy(myObj, {
  get: (obj, prop) => obj[prop] === "" ? null : obj[prop],
});

// proxyObj.value1
//   => 'bacon'
// proxyObj.value2
//   => null

While the Proxy solution is creative, the iterative solutions provided above are generally more straightforward and preferable in most scenarios.

Answer №2

If you're finding that the solutions provided here are not quite meeting your needs, I have an alternative approach that I used to solve this issue. My solution involved using a combination of JSON.stringify and JSON.parse with a specified reviver function to manipulate the strings.

let data = {
  value1: 'bacon',
  value2: '',
  value3: 'lard',
  value4: '',
  value5: 'cheese',
};

data = JSON.parse(JSON.stringify(data), (key, value) => {
    return value === '' ? null : value;
});

Answer №3

An additional demonstration of iteration.

const object = {
  item1: 'ham',
  item2: '',
  item3: 'butter',
  item4: '',
  item5: 'milk',
};

Object.keys(object).reduce((accumulated, property) => {accumulated[property] = object[property] === '' ? null : 
object[property]; return accumulated; }, {})

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

Having trouble writing Jest test cases for a function that returns an Observable Axios response in Nest JS

I'm relatively new to the NestJS + Typescript + RxJs tech stack and I'm attempting to write a unit test case using Jest for one of my functions. However, I'm uncertain if I'm doing it correctly. component.service.ts public fetchCompon ...

Replicating entities in TypeScript

I am currently developing an Angular 2 application using TypeScript. In a User Management component, I have implemented a table that displays all the users in my system. When a user is clicked on within the table, a form appears with their complete set of ...

leveraging services in Angular 4's router system

Below is the route setup: export const routes: Routes = [ {path: '', redirectTo: '/login', pathMatch: 'full'}, {path: 'login', component: LoginComponent, canActivate: [dbs.ConfigGuard]}, {path: '**& ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

Using TypeScript: Retrieve enum type value in type definition

I'm encountering an issue while attempting to define a specific type based on the value of an enum. enum E { A = "apple", B = "banana", C = "cherries" } // Defining the type EnumKey as 'A' | 'B ...

Simple steps to turn off error highlighting for TypeScript code in Visual Studio Code

Hey there! I've encountered an issue with vscode where it highlights valid code in red when using the union operator '??' or optional chaining '?.'. The code still builds without errors, but vscode displays a hover error message st ...

Converting objects to arrays in Typescript: A step-by-step guide

Can anyone assist me in converting a string to a Typescript array? Any help would be greatly appreciated. Take a look at the following code snippet: private validateEmptyOption(): any { console.log("CHECKED") let isValid = true; this.currentF ...

Exploring the use of .pipe with Angular Jest for testing

Currently, I am trying to test the following .ts file: create(entityResourceID, params: any): Observable <any>{ const url = `${this.apiUrl}/${entityResourceID}/assignee`; return this.http.post(url, params).pipe( map(() ...

When the React Native Expo app is running, the TextInput form is covered by the keyboard

When I launch the app using expo and implement my DateFormInput component, the issue of Keyboard covering TextInput arises. Despite trying packages like "@pietile-native-kit/keyboard-aware-scrollview", "@types/react-native-keyboard-spacer", "react-native-k ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Encountering issues with accessing a variable before its initialization in the getServerSideProps function in

Currently, I am working on setting up Firebase and configuring the APIs and functions to retrieve necessary data in my firebase.tsx file. Afterwards, I import them into my pages/index.tsx file but I am encountering an issue where I cannot access exports af ...

I'm unsure how to utilize the generic type in this particular scenario. It's a bit confusing to me

Recently, I delved into TypeScript generics and applied them in specific scenarios. However, I encountered some challenges. While working with two different interfaces, I faced a need for flexibility. For instance, I needed to make server requests. func ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

When using TypeORM's save() method with an array of objects, the @PrimaryColumn() annotations are ignored, resulting

My current situation involves an entity called Point: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; @IsUUID() @PrimaryColumn({ type: 'uuid', ...

"Learn the steps for accessing the most recent version of a ReactJS application from the server

I have my react app hosted on a Netlify domain. How can I ensure that users who have previously loaded older versions of the app are redirected to the most recent deployed version? ...

Finding the row index in an Angular material table

How can I retrieve the row index in an Angular material table? <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()&quo ...

The validator function in FormArray is missing and causing a TypeError

I seem to be encountering an error specifically when the control is placed within a formArray. The issue arises with a mat-select element used for selecting days of the week, leading to the following error message: What might I be doing incorrectly to tri ...

Exploring an array within an object using Typescript and React

As a newcomer to TypeScript and React, I have a project where I need to extract data from a JSON file (back-end) and display it on cards (front-end). I am trying to pass props using cards?.items.map, but I'm uncertain about the correct way to access ...

Tips to successfully save and retrieve a state from storage

I've encountered a challenge while working on my Angular 14 and Ionic 6 app. I want to implement a "Welcome" screen that only appears the first time a user opens the app, and never again after that. I'm struggling to figure out how to save the s ...

Access information from a different component within the route hierarchy

Suppose you have three components named A, B, and C with the following routing direction: A -> B -> C To retrieve data from the previous component (going from C to get data from B), you can use the following lines of code: In Component C: private ...