Tips for excluding a key in object literal notation when the value of the key is undefined

Currently, I am developing an RPG character generator that utilizes Redux. Within my reducer function, I aim to have the ability to update gear modifications and keep track of these changes. These modifications may include a rating, although it is not mandatory.

If the rating happens to be undefined, I would prefer not to store that information. Is there a way to exclude a key in object literal notation if the value is undefined?

The variable gearName will contain the name of the specific gear being modified.

In addition, mod is an object that includes details about the modification, such as +rating for fire resistance or other attributes.

Furthermore, rating represents a numerical value indicating the extent of the modification.

const purchaseGear = (state, action) => {
  const { gearName, mod, rating } = action.parameter;

  switch (action.type) {
    case MOD_GEAR:
      return {
        ...state,
        [gearName]: {
          ...state[gearName],
          mods: {
            ...state[gearName].mods,
            [mod.name]: {
              ...mod,
              rating
            }
          },
          cost: mod.cost * (rating || 1)
        }
    }
} 

Answer №1

A new pattern for object literals is being proposed by a developer.

const condition = true;
const data = {
    ...(condition ? {x: 10} : {}),
    y: 20,
};
    // {y: 20}

To apply this pattern in a specific case, you can do something like this:

...(value !== null ? {key: value} : {})

Note that this approach relies on the Object spread/rest proposal which may not be supported in all environments.

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

A simple guide on displaying the context menu for a specific row within a gridView

I'm working with a gridview that is bound to a data table. I am trying to add a context menu for rows that meet a certain condition. In the RowDataBound event, I have the following code: if (e.Row.Enabled == true && e.Row.Cells[6].Enabled == ...

How can constants from components be defined in multiple ways when imported? (specifically in React)

Although I have a good understanding of React and Javascript, I struggle to articulate my question effectively. I will provide examples in the hopes that someone with more expertise in the field can assist me. For instance, when using import { useRef, use ...

What sets apart `lib.es6.d.ts` from `lib.es2015.d.ts` in TypeScript?

I'm a bit confused about ES6 and ES2015. In TypeScript, there are two type declarations available for them: lib.es6.d.ts and lib.es2015.d.ts. Can someone explain the difference between these two? And which one is recommended to use? ...

Looking to incorporate HTML5 videos into a responsive Bootstrap carousel?

I've been working on creating a carousel that includes videos. When it comes to images, everything works smoothly as they are responsive even in mobile view. However, I'm encountering an issue with videos where the width is responsive but the hei ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Creating static websites through dynamic processes

I am currently developing a website generator using React, Express/Node, and MongoDB. The process involves creating a user interface to collect content and styling parameters through a multi-step form, followed by a dashboard for users to manage settings. ...

How to utilize Vue.js 3, Axios, and Express to showcase data retrieved from an array or

Trying to display a single post fetched from an express API using Vue has been challenging. The issue lies in the fact that the values declared in the template for post.title & post.body are not being displayed as expected when accessing post.value. ...

Unable to append a notification following an XHR request in Rails

When a file is added and redirected correctly, no notice is displayed. However, if xhr is not used, the notice will appear. application.js var files = evt.target.files || evt.dataTransfer.files; // files is a FileList of File objects. List some properti ...

I aim to arrange levels within a specified time interval in an array format

I am currently working with angular js and moment.js. I am in the process of generating levels for a line graph, specifically needing to set some intervals for the x-axis values corresponding to hours. At the moment, I am using these x-axis values statical ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...

What could be causing json_decode to return NULL in this scenario?

I have a custom array that I've created with the following structure: [{ "assetPreviewUrl":"pic1.jpg", "assetUrl":"pic2.jpg" }, { "assetPreviewUrl":"pic3.jpg", "assetUrl":"pic4.jpg" }] My approach involves stringifying this array and ...

Tips for transferring data from a controller to $scope in the MVC architecture with AngularJS

I'm a beginner when it comes to AngularJS, currently working with an MVC5 application. I have set up a module and controller in the Angular JS for this application. Within my customer controller in MVC5, I have an action called "View" where I need to ...

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

Looking for the temporary folder created by the nodejs filesystem?

After encountering path issues with writing values from a textarea to a file using fs, I turned to stackoverflow and discovered that the path should be a tmp folder. Following this advice, the terminal indicated success with the process. However, now I am ...

Exporting variables in Node.js using module.exports

I am facing an issue with two JavaScript files, a1.js and utils.js. Here is the content of the files: a1.js const namet = require('./utils.js') console.log(name); utils.js console.log('utils.js'); const name ='Mike'; modul ...

Cannot utilize structuredClone() on the value of the reference variable

I am looking to implement the structuredClone() function in my Vue application. I want to use it for creating a deep clone without resorting to methods like stringify and parse or third-party libraries. In my setup function, the following code works fine: ...

JavaScript effectively divides multiple child dropdowns with the main dropdown, thanks to Bootstrap innovation

I have implemented a jQuery function to dynamically change multiple child dropdowns based on the selected value of the main dropdown. For reference, you can view the image here. However, I encountered an issue when applying the Bootstrap styles "form-con ...

Difficulty loading AngularJS 1.3 page on Internet Explorer 8

Being an avid user of Angular, it pains me to even bring up the topic of IE8, a browser that many consider to be pure evil and deserving of extinction. Despite my reservations, I am experiencing difficulties with loading Angular 1.3 in IE8. The page break ...

Difficulties in Configuring Testacular Integration with Jasmine and Angular

I'm in the process of setting up a unit testing environment for my project and encountering some difficulties. Specifically, I am attempting to utilize Testacular with Jasmine to test my AngularJS code. One of the challenges I am facing involves a mo ...