Generate a JSON object based on the request.body information

Currently using NodeJs along with Express for building a REST API. The functionality is all set up and running smoothly, but I'm facing an issue in comprehending how to iterate through the request.body object and validate its fields for any undefined or empty values. My goal is to construct a new object containing only the valid data.

The structure of request.body appears as follows:

{ 
  key: 'value',  
  otherKey: 'otherValue',
  oneMoreKey: '',
  oneMoreKey2: undefined,
  oneMoreKey3: null
}

Ultimately, the desired format of my object should be:

let contactData = Object.assign({},{
        'key': 'value',
        'otherKey': 'otherValue'
    })

I would greatly appreciate any advice or assistance on this matter.

Answer №1

JavaScript

function createCleanObject(originalObject) {
    var cleanObject = {};
    for (var prop in originalObject) {
        var val = originalObject[prop];
        if (val) cleanObject[prop] = val;
    }
}

Explanation

To begin, you can create a new clean Object

var cleanObject = {}; // equivalent to new Object();

Next, loop through all properties of the object using a for loop.

for (var prop in originalObject)

Retrieve the value of that property

var val = originalObject[prop];

If the value is Truthy, add the property to the new Object

if (val) cleanObject[prop] = val;

Keep in mind that this approach will exclude the false value. To include it in the new Object, modify the if statement to

if(val || val === false)

Additionally, if the Object being copied also inherits from another Object, it may have additional properties. If you wish to exclude them, adjust the if statement to

if(val && originalObject.hasOwnProperty(val))

Also Remember for(var item in object) != for(var item of list)

The in keyword is used to iterate over an object's properties, while of is used to iterate over an iterable (e.g., list). Furthermore, in is universally supported across browsers, whereas of lacks support in Internet Explorer.

Answer №2

my_var = {
       var1: request.body[var1] || 'default',
       anotherVar: request.body[anotherVar] || 'default',
       oneMoreVar: request.body[oneMoreVar] || 'default'
       ...
}

details on how the OR (||) operator functions can be found at Explanation of JavaScript's OR (||) variable assignment mechanism

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

What is the most effective way to organize an array according to a key function that is computationally intensive?

After posting this question regarding sorting an array with a key function, it became evident that utilizing a comparison function was inevitable. The challenge at hand includes: Having a resource-intensive key function that needs to be transformed into ...

Run a Javascript function when the expected event fails to happen

I currently have this setup: <input type="text" name="field1" onblur="numericField(this);" /> However, I am struggling to figure out how to execute the numericField() function for the element before the form is submitted. I attempted using document ...

Incorporate the variables specified in the parent PHP file into the PHP code being received through

I am currently working on a project that involves enabling a user to view his profile upon login. However, I am aiming to have the dashboard load all other profile pages through ajax, such as the view profile and edit profile pages. My progress so far inc ...

When the parent element's CSS property is set to display: none, ng-repeat fails to function

I have a division with a specific class in the CSS named display: none;. When I click on a button, I switch the class using a toggle class feature called ng-class="vm.showing ? 'zoomIn' : 'zoomOut'". The issue arises when Angular does n ...

Why Bootstrap 4 collapse feature is not functioning correctly within a ReactJS map component?

I am currently working on a project that requires implementing a collapse feature. The idea is to display all available content when the user clicks the Read More button (which is functioning as intended for collapsing). However, I am facing an issue where ...

What is the best way to activate an event listener only after a button has been clicked?

Currently, I am developing a game that includes a timer and an event listener that notifies the user not to switch tabs. However, I am facing an issue where the event listener triggers before the game's start button is clicked. Is there a way in JavaS ...

Is there a way to work around coursera's keyboard input verification using JavaScript?

Is it possible to bypass Coursera's keyboard input verification using JavaScript? For example: What methods or techniques could be used to accomplish this? ...

Getting the most out of the fastest-validator package: Implementing multiple patterns and custom messages

Utilizing the powerful fastest-validator library for validation purposes. I have a requirement where the password field must contain at least one character and one number. Along with this, I am in need of specific messages for validating these conditions ...

Modifying Arrays with Different Data Structures in JavaScript

I am interested in implementing the following scenario: var A = ["Jon","Brad","Rachel"]; var B = ["Male","Male","Female"]; var C = [ {"Jon","Male"}, {"Brad","Male"}, {"Rachel","Female"} ] Can you guide me on how to retrieve var C using javascrip ...

My Application Failing to Cache in Nginx

I'm currently in the process of configuring caching for my ExpressApp and its rendered Jade files using Nginx. While running a Google Pagespeed Insight test and monitoring the pm2 logs of my application, I noticed that Images and HTML are still being ...

What is the method for accessing the AG-Grid Grid API beyond the Vue component?

In my application, I have a component called Home and another one called AgGrid. The AgGrid component is displayed within the Home component, containing the actual AG-Grid. Here's how the Home component is structured: <template> <AgGrid :ro ...

Using Variables in JavaScriptExecutor with Selenium and C#

Currently in my Selenium tests, I am utilizing JavaScriptExecutor as shown below: IJavaScriptExecutor js = driver as IJavaScriptExecutor; string Pixels = "600"; js.ExecuteScript("arguments[0].style='transform: translateX(600px);'&q ...

Steps for successfully sending data to a MenuItem event handlerExplanation on how to

My issue arises when I attempt to render a Menu for each element in an array, as the click handlers for the items only receive the final element in the array rather than the specific element used for that particular render. The scenario involves having a ...

Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => { return <div className="navbar">this is navbar</div>; }; const Content = () => { return ( <div className="main"> <div className="background"> some content </div> ...

An issue arises when using JSON.parse() with regular expression values

I am encountering an issue with parsing a JSON string encoded with PHP 5.2 json_encode(). Here is the JSON string: {"foo":"\\."} Although this JSON string is valid according to jsonlint.com, when using the native JSON.parse() method in Chrome a ...

MapBox notifies when all map tiles have finished loading

Currently, I am utilizing the Mapbox GL JS API to manipulate a Mapbox map. Prior to sending my result (which is a canvas.toDataURL) to the server via HTTP, I must resize my map to a larger resolution and then use fitbounds to return to the original points. ...

Translate this Python JSON string "column1=value1;column2=value2" into a dictionary format: {"column1":"value1","column2":"value2"}

I have a simple request. I need to change this structure: "column1=value1;column2=value2" to JSON format like this: {"column1":"value1","column2":"value2"} If you know the best way to do this in Python, please share. Thank you in advance. ...

Tips for activating an HTML input field using Javascript

I am currently using localStorage to store a string input by the user as a title, which will be saved for future visits. I would like to implement a button that allows the user to delete the displayed text (from localstorage) and enables the input field fo ...

A guide to eliminating TextRow and inserting a string into JSON using NodeJs

To remove TextRow and add the string true to JSON in NodeJs, I have included the following code: NodeJs Code: function groupBy(objectArray, property) { return objectArray.reduce(function (acc, obj) { let key = obj[property] if (!acc[key]) { ...

How can I create a Discord bot command that ignores case sensitivity?

I wrote a custom "roleinfo" command for my Discord bot, but I'm struggling to make the role search case insensitive. Here is the code snippet: const Discord = require("discord.js"); module.exports.run = async (bot, message, args) => { //Me ...