Eliminate unneeded null and empty object data attributes within Vue.js

When sending object data to an API, I have multiple states but not all of them are required every time. Therefore, I would like to remove any properties from the object that are null or empty strings. How can I achieve this?

export default {
  methods: {
    sendData() {
      axios
        .post("api", this.$store.state.data)
        .then((response) => console.log(response))
        .catch((error) => console.log(error));
      console.log(this.$store.state.data);
    },
  },
  mounted() {
    this.sendData();
  },
};

In this scenario where I access store state data, my goal is to only transmit the non-empty values and exclude those with empty values.

Answer ā„–1

To filter out empty fields from an object, utilize the .reduce() method on the keys of the object:

let cleanData = Object.keys(this.$store.state.data).reduce((result, key) => {
  if (data[key]) {
    result[key] = data[key];
  }
  return result;
}, {});

axios.post("api/data", cleanData);

Answer ā„–2

To eliminate any null or undefined data from an object, simply iterate through its keys and ascertain if their values are null/undefined, subsequently removing them if necessary.

Object.keys(yourObj).forEach(k => [undefined, null].includes(yourObj[k]) && delete yourObj[k] )

If there are additional values you wish to verify, you can append them to the array within the forEach loop.

Subsequently, you can transmit this updated object as the body of your POST request.

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

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

Node.js application abruptly halts without warning

I am currently working on a script to parse bitcoin blockchains using an asynchronous queue function from a popular library. However, I have encountered an issue where the code seems to stop without any error message during processing. What could be causin ...

Retrieve the scrolling height in Vue.js 2 window

I need to apply the sticky class to the navbar when a user scrolls down, and remove it when they scroll back up. To achieve this, I am attempting to calculate the scrolled height. Currently, my code looks like: mounted(){ this.setUpRoutes(); wind ...

Is the CSS scale activated by mouseover or click?

My CSS code successfully scales images, but the issue is that it affects every image on the page. I am looking for a solution to apply this CSS only when the user hovers over or clicks on an image. The challenge is that images are added by non-technical w ...

Getting content for a component by clicking a button outside the component in Vuejs ā€“ here's how!

My challenge is to update the content of a modal whenever a button outside of the component is clicked. The goal is to update an item slug that will be used to fetch content from an API. This task is within Vuejs, and I am still learning how to work with ...

Troubleshooting issues with gh-pages in Nuxt.js

Working on a project in nuxt.js was going smoothly until I tried to deploy it on gh-pages using npm install gh-pages --save-dev. After adding some code to packed.json, everything seemed fine and I could view my project on gh-pages: However, all of a sudde ...

Discovering the technique to interact with obscured objects through a haze of PointsMaterial in three.js

Is there a property that allows objects behind a fog of multiple points to be clickable? I want to be able to click on objects even when they are obscured by the fog. Below is the code I am using to create and animate the fog: const loadFogEffect = () =&g ...

Pass a bespoke object back to the GraphQL resolver

In my Node-Express backend server with GraphQL setup, I am working on providing a custom object as output for a GraphQL resolver. The usual Sequelize approach hasn't worked for me in this case, so I'm exploring new methods. const RootQueryType = ...

Importing Global Sass Styles in Nuxt 3 for Static Assets

I'm currently attempting to import a global Sass stylesheet from the /assets directory in order to utilize variables and mixins defined there throughout the components. My current configuration in nuxt.config.ts is as follows: import { defineNuxtConfi ...

What is the antonym of 'appear' when it comes to Vue transitions?

Iā€™m currently working on a modal component that utilizes the 'v-if' attribute to determine its visibility. In the Vue documentation, it mentions using 'appear' for transitions (https://vuejs.org/guide/built-ins/transition.html#transi ...

Optimal method for retrieving data from asynchronous functions in JavaScript

Currently, I am using the twit library for nodejs which has async calls. In my code, I have created functions like the following: function getUserFromSearch(phrase) { T.get('search/tweets', { q: phrase+' lang:pt', count: 1 }, funct ...

Click the "Add to Cart" button to make a purchase

Recently, I've been working on modeling an add to cart feature using jQuery. However, I have encountered a small issue that I'm trying to troubleshoot. When I click the mybtn button, the model displays and functions correctly, but there seems to ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...

What is the best way to connect my products on an ecommerce site with hundreds of images?

Despite thoroughly searching the internet, I have been unable to find a solution to my dilemma. I am creating a platform that showcases a lengthy list of products on the website. Additionally, I have a database of pictures stored locally that need to be ...

Stopping a requestAnimationFrame recursion/loop: Tips and Tricks

I am developing a game using Three.js with the WebGL renderer that goes into fullscreen mode when a play link is clicked. To handle animations, I utilize the requestAnimationFrame method. The initialization of the animation process looks like this: self. ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

Nuxt Page Featuring One Exclusive Product

I am just getting started with Nuxt and I'm in the process of creating a Single Product. I have some questions: How can I generate multiple pages using SSR and create a unique HTML for each page? Should CSR be developed first before implementing SSR, ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...