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

NavLinkButton - add style when active or selected

I'm working with a list of NavLinks: const users = Array.from(Array(5).keys()).map((key) => ({ id: key, name: `User ${key}`, })); <List> {users.map((user) => { return ( <ListItem disablePadding key={user.id}> ...

Navigating to a particular value in Vue: A step-by-step guide

In my Vue application, I have a basic table structure: <tbody> <tr v-for="(item, index) in items"> <td> ... </td> </tr> </tbody> The items are dynamically added using the unsh ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

"Enhance your website with interactive jQuery lightbox buttons for easy navigation

As I explore the jquery lightbox plugin, I find it to be quite straightforward. However, I am curious if there is a way to make the "previous" and "next" buttons of the plugin function without the images needing to be named sequentially (e.g., "image1.jpg, ...

Tips for preventing the use of nested functions while working with AJAX?

Consecutively making asynchronous calls can be messy. Is there a cleaner alternative? The issue with the current approach is its lack of clarity: ajaxOne(function() { // do something ajaxTwo(function() { // do something ajaxThree() }); }); ...

What is the process for updating information in Vue.js?

I need assistance with displaying the updated data in a modal. When I trigger the testing(data) function through a click event, the data appears correctly within the function. However, the template does not update and still shows the previous data. How can ...

Harmonizing various client viewpoints in a ThreeJS scene featuring a unified mesh structure

I am fairly new to ThreeJS and I am curious to know if it is possible to achieve the following, and if so, how can it be done: Two web browser clients on separate machines want to load the same html-based Scene code, but view it from different perspective ...

Sending JavaScript variables to an external CSS file

I've been searching for a solution without much luck. I must admit, my CSS skills are pretty basic. Currently, I am using Muxy.io to manage notifications for my livestreams. The platform allows customization of notifications through HTML and CSS file ...

What is the best way to achieve this in Node.js/Express using Redis? Essentially, it involves saving a callback value to a variable

Here is the data structure I have set up in redis. I am looking to retrieve all values from the list and their corresponding information from other sets. Data structure : lpush mylist test1 lpush mylist test2 lpush mylist test3 set test1 "test1 value1" ...

Tips on enlarging the header size in ion-action-sheet within the VueJS framework of Ionic

Recently I started using Vue along with the ionic framework. This is a snippet of code from my application: <ion-action-sheet :is-open="isActionSheetOpen" header="Choose Payment" mode="ios" :buttons="buttons&qu ...

The checkbox is not showing the check mark accurately

I am currently working on a React form where I am trying to retrieve the status of a checkbox element from local storage using the useEffect hook. const [checkbox, setCheckbox] = useState(false); useEffect(() => { setCheckbox(localStorage.getItem(&ap ...

Troubleshooting a Node.js server issue with a two-dimensional array

I am currently facing an issue with submitting a form that contains two-dimensional array fields on a post request in node.js. The problem lies in the fact that the server side is receiving a one-dimensional array with all the values combined. Below is an ...

Data is not being successfully passed through Ajax

Having some issues with passing data through ajax. I've used this method multiple times before without any problems, but now it's not returning anything. Here is the javascript code: $('#contactformbtn').click(function(){ var full ...

Successfully resolved: Inability to dynamically adjust button color according to its state

Currently I am working on a feature where a button changes color when it is disabled, but also has a custom color when enabled. Here is the code snippet I am using: Despite setting blue text for the button, it remains blue even after becoming disabled. Ho ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

Is there a way to dynamically adjust the height of a DIV block?

I have a situation where I need the height of one div to automatically adjust based on changes in the height of another div. var height = jQuery('#leftcol').height(); height += 20; jQuery('.rightcol-botbg').height(height); Unfortun ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

I am looking to optimize my WordPress posts to load in increments as the user scrolls down the page, similar to how Facebook does

I am looking to implement a feature on my WordPress post where the content loads a few at a time as the user scrolls, similar to Facebook. Specifically, I would like my webpage to automatically load 10 posts and then continue loading 10 more as the user re ...

The tablet is having trouble playing the mp3 audio file

When clicking on an mp3 audio file, I want the previous file to continue playing along with the new one. While this works perfectly on browsers with Windows machines, there seems to be an issue when using a tablet. The second mp3 stops playing when I clic ...

Arranging and moving list elements without the use of jQuery UI (or any jQuery libraries at all?)

I have been searching for a JavaScript plugin that offers the same functionality as jQuery UI Sortable, which is the ability to drag and drop items to reorder them. In my case, these items are <li> tags. I prefer not to use jQuery UI because it is h ...