Get the object length in angularjs is undefined

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.


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>

Combining some of these answers into

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

seems to work

<div ng-show="(furry.animals | numkeys) > 10">lots of furry animals</div>

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()"

Tags:

Angularjs