"Sweet syntax" for assigning object property if the value is true

In the project I'm working on, I find myself dealing with a lot of parsing and validating tasks. This often results in 5-10+ lines of code like if(value) object.value = value.

I considered using

object.value = value || (your favorite falsy value)
approach, but then the property ends up with a falsy value.

Here's an example (not actual production code):

let filter = {}

let thing = ctx.query.thing

thing = Validation.validateThingy(thing)

if(thing) filter.thing = thing

// +50 more parameter parsing/request body parsing

return DB.find(filter).then(etc...)

Is there a more elegant solution to handle this situation without resorting to || or iterating over the object's properties to filter out falsy values?

Answer №1

If you want to set a value using a function, you can pass an object along with the key and value parameters.

function assignValue(object, key, value) {
    if (value) {
        object[key] = value;
    }
}

// example of how to use the function
let data = {};

assignValue(data, 'property', Validation.validateField(ctx.query.property));

Alternatively, you have the option to include the validation process inside the function itself.

function assignValue(object, key) {
    var value = Validation.validateField(ctx.query[key]);
    if (value) {
        object[key] = value;
    }
}

// example of how to use this updated function
let data = {};

assignValue(data, 'property');

Answer №2

One potential approach is to take advantage of short circuit evaluation with && and use

thing && (filter.thing = thing)
, but in my opinion, it would make the code harder to read. Personally, I believe sticking with your original implementation or creating a separate function would be more effective choices.

Answer №3

What if we try this:

   item && (filter.item = item);

Answer №4

Oops, my mistake, the original poster clearly mentioned:

...without using an || operator or iterating over the object's properties to filter out the false values?

...I must have overlooked that. The following code accomplishes exactly that.

For those reading this in the future without knowing the OP's preference:


You can gather the values in an object and then utilize a utility function to iterate through those values and only copy the truthy ones:

let values = {};
values.thing = Validation.validateThingy(ctx.query.thing);
// +50 others...
let filteredValues = copyTruthy({}, values);
return DB.find(filteredValues).then(/*etc...*/);

where copyTruthy is defined as:

function copyTruthy(destination, source) {
    for (const key of Object.keys(source)) {
        if (source[key]) {
            destination[key] = source[key];
        }
    }
    return destination;
}

Answer №5

A ternary expression can be used as a standalone statement and will function properly.

If value is true, set object.value to that value; otherwise, set it to null:

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

Ensure that a specific value is maintained for a property of an element throughout its animation

There are two distinct types of components that I am working with, which I will refer to as .a and .b. It is possible that these components have been assigned certain CSS animations. I do not have the ability to control these keyframes, whether they are a ...

Cookie Cutter Chrome Extensions

Is there a way to create a cookie that can be shared between my plugin and contentPage? I've tried creating one but it doesn't seem to appear on the cookie list of the tab page. Any suggestions or ideas on how to achieve this? ...

Tips for creating text that adjusts to the size of a div element

I'm currently working on developing my e-commerce website. Each product is showcased in its own separate div, but I've encountered a challenge. The issue arises when the product description exceeds the limits of the div, causing it to overflow ou ...

Only Chrome causing my JavaScript execution to freeze due to Ajax

When using Ajax, it is supposed to be asynchronous, but for some reason, it seems like it's either stopping or pausing my JavaScript execution and only resuming once the response is received. Here is an example of HTML value: <input value="foo" d ...

Is there a way for me to generate a preview thumbnail for my video?

Looking to add a preview effect to video thumbnails when users hover over them, displaying a series of frames from the video. Are there any jQuery plugins or tutorials available for creating this effect? ...

Removing data with the click of a button

I have successfully implemented a feature where clicking the "add to my stay" button displays the name and price data. Subsequently, it automatically changes to a remove button when clicked again for another addon. If I press the remove button of the first ...

Data obtained from the server includes JSON objects along with quotes and regular expressions

While analyzing the functionality of a search page server through element inspection, it was observed that requests are sent via POST with JSON parameters. To verify this observation, I recreated the same POST request using Insomnia with identical paramete ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...

How to generate flexible arrays using an established array?

Currently, I am working on creating a new array from an existing one. The structure of my current array is outlined below. How can I ensure that adding a new object results in a new array starting from that point? myArray: [{ anima ...

Incorporating navigation controls into a modal window

I have successfully created a sign-in modal, but now I'm looking to include buttons at the top. One button should redirect users to register/sign up, and the other button should lead them back to the sign-in modal, as shown in the image I've link ...

Progress bar indicating the loading status of an AJAX script

I am facing a challenge with creating a progress bar in AJAX. The entire page is loaded through AJAX, and one of the webpage elements uses AJAX to fetch large rows from the database. I have attempted to implement a progress bar within this script using a ...

Tips for choosing Week Range values with Selenium WebDriver

Currently, I am working with Selenium WebDriver and I am trying to figure out how to select week range values from a dropdown menu at once. I have a dropdown called Period, which, when selected, automatically reveals additional dropdowns for From week and ...

Sending various values to a JavaScript function

I am working with a function that looks like this: //Function Call with Single Parameter responses(baseURL); //Function Definition function responses(baseURL) { $.ajax({ url: baseURL, type: "get", cache: false, header ...

Obtaining the initial row information from jqGrid

If I use the getRowData method, I can retrieve the current cell content instead of the original data before it was formatted. Is there a way to access the original content before any formatting transformations are applied? Just so you know, I am filling t ...

What is the best way to implement a fadeout or timeout for success and warning alerts in OpenCart 2.2?

Is there a way to set a timeout for alert boxes in Opencart 2.2 so that they disappear after a few seconds? I've tried the code below, but it didn't work out. Alternatively, is it possible to make the popup disappear when clicking anywhere on the ...

Using v-for to pass two properties to a single component in VueJS

Hey there! I'm trying to create a v-for loop with a component that has two different props COMPONENT <template> <div class="bg-light rounded p-2 px-5"> <h5> {{ number }}</h5> <h3>{{ item }} ...

Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently. I have 2 JSON files: images.json { "imageName": "example.jpg", "imageTags": ["fun","work","utility" ...

delivering axios response to display the page

I have a code snippet that requests data from an external API using axios and I want to incorporate the response into my rendered page. Here is my code: //Snippet from my controller required in main routes exports.recordBySlug = async (req, res, next) =&g ...

What methods can Cypress use to validate content containing hyperlinks?

My current task is to develop an automation test that confirms the presence/display of content containing a hyperlink embedded within text. Please refer to the screenshot I have provided for better understanding, as it illustrates the specific content encl ...

Postman sends requests by utilizing AJAX and adhering to the same origin policy

I recently came across a Chrome extension called Postman that has proven to be incredibly useful. This tool is particularly handy for those working with RESTful applications. One thing that has puzzled me is how Postman is able to successfully send POST r ...