1

I am sending object data to some API. I have many states and not every one is required every time, so I want to remove any properties from the object that are null or an 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.

0

2 Answers 2

2

You can use the .reduce() method on the object's keys to create an object with only the non-empty fields:

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

axios.post("api", filledData);
Sign up to request clarification or add additional context in comments.

Comments

0

You can remove null or undefined data from an object by looping through its keys and checking whether their values are null/undefined, and deleting them if so.

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

If there more values you would like to check for, you can add them in the array that's withing the forEach loop.

You can then pass this new object to the body of your POST request.

1 Comment

This will update the original object, which is usually undesirable. In the case of the something like a state store, it will break it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.