Get the object length in angularjs is undefined

后端 未结 8 2258
梦谈多话
梦谈多话 2021-02-19 03:57

How can I get the object length ?

In console my object looks like this:

Object {
 2: true,
 3: true,
 4: true
}

.length w

相关标签:
8条回答
  • 2021-02-19 04:30
    var keys = Object.keys(objInstance);
    var len = keys.length;
    

    Where len is your "length."

    There may be circumstances I haven't thought of where this doesn't work, but it should do what you need, given your example.

    0 讨论(0)
  • 2021-02-19 04:31

    You don't want to repeat that Object.keys(obj) everywhere you want to get the length, as the code might get pretty messy. Therefore just put it in some personal project snippet library to be available across the site:

    Object.prototype.length = function(){
        return Object.keys(this).length
    }
    

    and than when you need to know object 's length you can run

    exampleObject.length()
    

    there's one problem with above, if you create an object that would have a "length" key, you will break the "prototype" function:

    exampleObject : { length: 100, width: 150 } 
    

    but you can use your own synonym for length, like "l()" instead of "length()"

    0 讨论(0)
  • 2021-02-19 04:39

    You could also use a filter

    Edit:

    app.filter('objLength', function() { 
     return function(object) { 
      return Object.keys(object).length; 
     } 
    });
    

    Old Answer:

    app.filter('objLength', function() {
     return function(object) {
      var count = 0;
    
      for(var i in object){
       count++;
      }
      return count;
     }
    });
    

    And then use it maybe like this

    <div ng-hide="(navigations._source.languages | objLength) == 1"> content</div>
    
    0 讨论(0)
  • 2021-02-19 04:41

    Short variant Object.keys($scope.someobject).length

    0 讨论(0)
  • 2021-02-19 04:42

    it can be get by below code simply

    var itemsLength = Object.keys(your object).length;

    0 讨论(0)
  • 2021-02-19 04:44

    We can also add a small validation if we are retrieving data from API.

    app.filter('objLength', function() { 
     return function(object) { 
      return object ? Object.keys(object).length : "";
     } 
    });
    
    0 讨论(0)
提交回复
热议问题