"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

Guide to swapping images on button click in HTML with dynamically changing image URLs retrieved from the server

I am a beginner in client-side scripting and new to Stack Overflow. I am looking for guidance on how to change an image within a div element upon clicking a button or anchor tag. Here is the code snippet I have written to achieve this: $scope.captchaCha ...

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...

Troublesome CSS conflicts arise when using minified assets with AngularJS and Webpack

After transitioning my Angular project to the Webpack build system, I encountered issues with Angular Dependency Injection in the JS source code. Surprisingly, now I am facing JS errors that are targeting CSS files, leaving me completely bewildered about w ...

The ng-submit() directive in Angular does not trigger submission when the "Enter" key is pressed in a text field

I have created a basic form using Angular where I want the ng-click function (updateMsg({name: name,room: room})) to be triggered when the user enters a value and then presses enter key. Unfortunately, the current code does not work as expected. The funct ...

Tips for concealing the Bottom bar action in React Native

Currently facing an issue with React Native - I need to hide the bottom action bar located just below my tab bar navigation. I'm trying to create a clone of the Disney + App and this particular problem has me stuck: Here's the bottom part of my ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

Update the useState function individually for every object within an array

After clicking the MultipleComponent button, all logs in the function return null. However, when clicked a second time, it returns the previous values. Is there a way to retrieve the current status in each log within the map function? Concerning the useEf ...

Accessing JSON data from a URL for use within a specific context

I am currently utilizing the request module within Express to fetch a JSON file from a specified link. var url = 'https://api.github.com/users/google/repos'; request.get({ url: url, json: true, headers: {'User-Agent': &apo ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

Convert the jade file to an HTML file while keeping the original file name

I'm currently attempting to configure Jade in a way that allows me to save my Jade files as HTML files while retaining the same file name. For example, I would like the file views/index.jade to be saved as dist/index.html This should apply to all ad ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

What is the best way to extract text from a list item in an unordered list (

I am trying to search a ul list that populates a ddSlick dropdown box. ddSlick adds pictures to list items, making it a visually appealing choice. To see more about ddSlick, you can visit their website here: Here is the code I am using to loop through the ...

Modify the content of a div by clicking on a word or link using Javascript

I'm attempting to create a clickable word (page 2) that acts as a link to display different div content. When the user selects option 2 and clicks the next button, they should be able to click the "Page 2" text to show the content with id="test1" (Cho ...

Issue: Unable to set headers after they have been sent while using express-fileupload in the application

app.post('/profile', function(req, res) { // save file if (req.files) { let sampleFile = req.files.sampleFile; sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) { if (err) ...

The issue with the material design checkbox change functionality not functioning as expected

Currently, I am attempting to dynamically set the state of checkboxes to either true or false. The following code snippet demonstrates what I have tried so far: for(var i = 0; i < bookmakers.length; i++) { $('#' + bookmakers[i].id + &apos ...

What is the proper way to reference an EJS function that is declared in a different EJS file?

document 1: jsfunction.ejs <% function testFunction() {return 42;} %> file 2: data.ejs <% include jsfunction.ejs %> <% testFunction(); %> result: ReferenceError: 1| <% include jsfunction.ejs %> >> 2| <% testFuncti ...

Navigating through different views in Angular 2 using UI Router and ng2 routing directly from

I am currently utilizing the UI-Router ng2 and attempting to change routes after a certain function is triggered. My code snippet looks like this: SomeFunction() { if(condition){ router.navigate(['/newRouteName']); } } It's ...

Interactive loading of datalist choices using AJAX in the Firefox browser

I have recently decided to replace the Jquery UI autocomplete function on my website with HTML5 datalists that load dynamic options. After researching this topic extensively, I came across various answers on Stack Overflow, such as How do you refresh an HT ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

Implementing fetch within a custom hook to display a loader within a return function

customFetch hook: import React, { useState, useEffect } from 'react'; const customFetch = (url, options) => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); useEffect(() => { (async () ...