EricTalv
EricTalv

Reputation: 1049

how to check if an object element is empty

I have a vue form and I am trying gather the data into an object, But when one object element is empty then Id want that field to be destroy'd.

this is my input field:

 <input v-model="fields.title" >

my data:

 data() {
        return {
            fields: {},
        }
    },

Basically right now what happens, is when I write something in my field, it creates title: 'data' and if i delete the text inside then that element still exists there so I am left with title: '', but I want it to be deleted if its empty.

I can recreate this like this:

computed: {
       destroyFieldWhenEmpty() {
           if (this.fields.title === ''){
               this.$delete(this.fields, 'title')
           }

But now If i have a lot of fields, I have to re-write that if statement for each input.

Thus, How could i go by doing this better?

Upvotes: 1

Views: 2325

Answers (2)

wangdev87
wangdev87

Reputation: 8751

- Use lodash isEmpty() function

_.isEmpty({}) // true
_.isEmpty({title: 'title'}) // false

- Use Object.keys().length

const obj = {...}

If obj is empty, Object.keys(obj).length equals to 0.

Upvotes: 1

Arab
Arab

Reputation: 87

So far I've got your problem, you're trying to delete an object from an array. if so you can filter data with your own business logic like this

const restFields = this.fields.filter(field => field.title.length > 0)

Upvotes: 0

Related Questions