vue.js proper way to determine empty object

You can just use length of inventory in v-if, like following:

<div id="element">
  <div v-if="!inventory.length">No item in inventory</div>
  <div v-for="(index, item) in inventory">
      {{item.key}}
      <button v-on:click="remove(index)">remove</button>
  </div>
</div>

Given that inventory variable is a hash and not an array, you can use any of the following to find it is empty and use that in v-if:

ECMA 5+:

Object.keys(inventory).length === 0

Pre-ECMA 5:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
}

As you are already using jquery, you can also do:

jQuery.isEmptyObject({}); // true

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>

<div id="element">

  <div v-if="isEmpty">No item in inventory</div>
  <div v-for="(index, item) in inventory">
      {{item.key}}<button @click="remove(index)">remove</button>
  </div>
</div>

<script type="text/javascript">
"use strict";
var vm;
$(function() {
    vm = new Vue({
        el: '#element',
        data: {
            inventory: {"id1" : {"key" : "val1"}, "id2" : {"key" : "val2"}},
            empty: false
        },
        methods: {
            remove: function(index) {
                Vue.delete(this.inventory, index);
                
            }
        },
        computed: {
           isEmpty: function () {
              return jQuery.isEmptyObject(this.inventory)
           }
       }
    });
});
</script>

After searching for a few minutes, I come up with a better solution to check whether the object is empty or not.

Object.keys( YOUR_OBJECT ).length == 0 // Check if it's empty.

It will return 0 if it's empty. If you want to check whether the array is empty or not you can definitely go for this solution below,

YOUR_ARRAY.length == 0  // Check if it's empty.

In my case it's an object, not array. So, it may also help. Happy coding :)

Tags:

Vue.Js