Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: determine observed object type (distinguish between array and object)

Tags:

vue.js

I have simple Vue instance:

<html>
  <body>        
    <div id="container">
      <input type="text" id="container" placeholder="enter text" v-model="value">
      <p>{{ value }}</p>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.11.10/vue.min.js"></script>
    <script>
      new Vue({
        el: '#container',
        data: {
          value: '',
          list: []
        },
        created: function() {
          console.log(typeof this.list); // i would like to determine type of underlaying object
        }
      });
    </script>
  </body>
</html>

https://codepen.io/anon/pen/KxVQEw?editors=1111

How to determine the type of the observed proprety in data lets say .list inside 'created' life cycle hook?

like image 302
IT Man Avatar asked Oct 23 '25 06:10

IT Man


2 Answers

typeof [] will return "object", same as typeof {}. If you want to know whether it's for example a JSON object or an array you can use varname.constructor.name:

console.log(typeof []) // object
console.log([].constructor.name) // Array

console.log(typeof {}) // object
console.log({}.constructor.name) // Object

In your case:

console.log(this.list.constructor.name) // Array
like image 93
dziraf Avatar answered Oct 25 '25 19:10

dziraf


Although there already is a working answer, I decided to use this alternative as it is less code: Array.isArray

Array.isArray([]) //true
Array.isArray({}) //false
like image 27
gekkedev Avatar answered Oct 25 '25 19:10

gekkedev