Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined.

In my code, I am initializing an object like this:

let aestheticEvaluation: AestheticEvaluation = {
    "altezza": aestheticEvaluationInfo.get('altezza').value,
    "peso": aestheticEvaluationInfo.get('peso').value,
    
    // other fields
    
    "notes": aestheticEvaluationInfo.get('notes').value,
};

The issue arises when some fields may have an undefined value. In such cases, these fields should not be added to the aestheticEvaluation object.

For instance, if the value of aestheticEvaluationInfo.get('altezza').value is undefined, the "altezza" field should not be included in the object.

I'm aware that I can use conditional statements to check for null values before adding each field to the object, but this would make the code more repetitive. Is there a way to handle this directly within the object initialization?

Answer №1

I have a couple of solutions in mind, so you can choose the one that best fits your needs.

  1. Instead of having undefined values, you can set default values such as an empty string '' or zero for numbers.
const object = {
    key: anotherObject?.attribute || ''
};
  1. Another approach is to set the object values first and then clean up the object by removing any undefined values:
const object = { key: value };

Object.keys(object).forEach(key => {
    if (!object[key]) delete object[key];
});

If there's anything I'm not understanding correctly, please let me know.

Answer №2

  const userEvaluation: UserEvaluation = {
   "height": userEvaluationInfo.get('height').value,
   "weight": userEvaluationInfo.get('weight').value,
   .... and so forth
  }


  for(const key in userEvaluation)
  { 
   if(!userEvaluation[key]) 
    delete userEvaluation[key]
   }

    !userEvaluation[key] = This will remove all falsy values like 
    null, undefined, 0, ''.
    If you only want to filter out undefined value, you can do 
   for(const key in userEvaluation)
    { 
     if(typeof userEvaluation[key] === "undefined") 
      delete userEvaluation[key]
    }

Answer №3

Looking at a unique approach to handling criteria declarations, this method simplifies the process by allowing each criteria to be declared only once and making it easy to interchange methods for obtaining values with just one line of code.

const beautyCriteria: string[] = [
  "height",
  "weight",
  "skinType",
  "photoaging",
  "blackheads",
  "varicoseVeins",
  "wrinkleLines",
  "nasolabialFoldsIntensity",
  "neckAgingDegree",
  "darkCircles",
  "eyeBags",
  "lowerThirdHypotonia",
  "cellulite",
  "hypertrophicKeloidScars",
  "Wood'sLight",
  "additionalNotes",
]

let beautyEvaluation: BeautyEvaluation = {}
beautyCriteria.forEach((criteria) => {
  const value = beautyInfo.get(criteria).value
  if (value){
    beautyEvaluation[criteria] = value
  }
})
//beautyEvaluation object is now populated with specified criteria/values
console.log(beautyEvaluation)

Answer №4

To ensure each value in the object is checked before creation, a function can be implemented as shown below.

// defining an object `aestheticEvaluationInfo` using the Map data structure
let aestheticEvaluationInfo = new Map();
aestheticEvaluationInfo.set('height', { value: { name: 'height'}});
aestheticEvaluationInfo.set('weight', { value: { name: 'weight'}});
.
.
.
// other fields omitted for brevity
aestheticEvaluationInfo.set('notes', undefined);

function createObjectWithValidValues(data) {
  let obj = {};
  for (const [key, value] of data.entries()) {
    if (value) obj[key] = value.value.name;
  }
  return obj;
}

console.log(createObjectWithValidValues(aestheticEvaluationInfo));

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

Issue encountered on server using next.js - FetchError: failed to process request for https://jsonkeeper.com/b/4G1G

Struggling to fetch JSON data from a link and destructure it for use on the website. I have a getStaticProps export function that extracts the data and I want to pass it into my default Home function to iterate through it. I have come across information ab ...

How can a false validation be conducted on knockout js?

Using knockout js, I have an input type checkbox and I want to trigger the "not true" action when this checkbox is selected. Here's what I have attempted: <input type="checkbox" data-bind="checked: !IsVisible"/> Unfortunately, this code isn&ap ...

Utilize the forEach method with a TypeScript wrapper class containing a list

After replacing a list with a wrapper class that allows for monitoring changes to the list, I noticed that I can no longer use the forEach statement to iterate over the class. let numberList = new EventList<number>([1,2,3,4]); numerList.forEach((elem ...

A TypeScript generic function designed to accept either two arrays or two objects, but not a combination of both

Currently, I am creating an extend function in TypeScript that has the capability to: Update the first object with the keys/values of the second when given two objects. Append the elements of the second array to the first array when provided with two arr ...

Utilize the $(#id).html(content) method to populate the following column with desired content

Here is a snippet of my HTML code: <div class="row margin-top-3"> <div class="col-sm-7"> <h2>NFTs</h2> <div class="table-responsive"> <table class="table table-bordered&qu ...

Updating switch data on click using Vuejs: A step-by-step guide

Could someone please explain to me how to swap two different sets of data when clicked? For instance, let's say we have the following data: data() { return { data_one: [ { name: "Simo", ...

Event triggered only upon initial click

I am experiencing an issue with my category list. When I click on a category to trigger an AJAX request for the first time, the request does not go through. However, when I click on the same category a second time, it works perfectly. Below is the code sni ...

Using OPTIONS instead of GET for fetching Backbone JS model data

Currently, I am attempting to retrieve data from a REST endpoint with the help of a model. Below is the code snippet that I am using: professors: function(id) { professor = new ProfessorModel({ id: id }); professor.fetch({ headers: { ...

Struggling to eliminate buttons upon clicking, but they persistently reappear (JavaScript, HTML)

I have encountered an issue with buttons in my table that I am struggling to resolve. Each row in the table contains a "Pack" action button, which when clicked, is removed to prevent accidental double-packing of items. Everything was functioning smoothly ...

Is it feasible to restrict a generic type using typeguard?

I'm currently working on refining a generic function, where the autocomplete feature recognizes that it's encountering a typeguard, preventing it from revisiting the same code block. I suspect that the issue lies in not restricting the type to th ...

Here is how you can pass two callback functions to React.cloneElement:

Recently, I encountered an issue where one of the callbacks passed to a child component using React.cloneElement was always present while the other was undefined. Specifically, activeRow was consistently available but deactivateRow remained undefined. I ...

What is the best way to incorporate a JavaScript library into my Angular 2 project?

I successfully installed Tween js using npm install tween, but I am unable to import it into my component. The library is located in node_modules/tween. I have tried: import * AS TWEEN from 'tween/tween.js' import {TWEEN} from 'tween&apos ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Leverage the power of integrating Power BI with Javascript to easily retrieve an

I have embarked on a mission to integrate PowerBI into my web application. Below is the code snippet that I have implemented: window.config = { instance: 'https://login.microsoftonline.com/', tenant: 'common', //COMMON OR YOU ...

Is it typical to experience a forced reflow violation and page offset?

After implementing a position: fixed on-scroll feature for my navbar, I noticed an error being thrown by the DOM stating: [Violation] Forced reflow while executing JavaScript took ms during every scroll event. It seems that this could be caused by layout t ...

Please refrain from displaying the POST response in Express

I have a simple Express API setup: app.get('/example', function(req, res) { if (req.body.messageid == 1) { res.send({message: "Message"}); } } The API returns a message to be displayed on an HTML page. To display the message, I created ...

Implement the useEffect() function to handle the loading of external JavaScript on the client-side, replicating the

I have encountered a challenge while trying to integrate a rich text editor into my NextJS project. Since there are no available React components for this specific editor and it operates solely on the client side, I am required to load the necessary JavaSc ...

Creating a custom useStorage hook to easily save a Set data type in local storage

I attempted to make modifications to the code found at this reference link: useLocalStorage hook my goal was to enable saving a Set() to localStorage. useLocalStorage.js import { useState, useEffect } from "react"; // Custom Hook export const ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...