Home > Back-end >  Vue.js remove object data if null or empty
Vue.js remove object data if null or empty

Time:06-20

i am sending object data to some api, i have many states, and not everyone is required everytime, so, i want to remove some data from object if it is null or empty string, how can i do 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();
},
 };

here, where i have store state data, i need to send only the filled values and not everything with empty values too, how can i realize this?

CodePudding user response:

Try to use the reduce method applied on object keys the return the object with non-empty fields:

export default {
  methods: {
    sendData() {
    
    let filledData = Object.keys(this.$store.state.data).reduce((acc,curr)=>{
       if(data[curr]){
          acc[curr]=data[curr]
        }
      return acc;
    },{})

 axios
    .post("https://covid19.devtest.ge/api/create", filledData )

....
  • Related