Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the object length in angularjs is undefined

Tags:

angularjs

How can I get the object length ?

In console my object looks like this:

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

.length will give me undefined. I just want to get the results = 3 for this case.

like image 920
godzo101 Avatar asked Mar 17 '15 19:03

godzo101


People also ask

How to check object length in angular html?

var keys = Object. keys(objInstance); var len = keys. length; Where len is your "length."

How do you find the length of a object?

Answer: Use the Object. keys() Method You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.

What is object keys js?

Object. keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.


2 Answers

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.

like image 121
Aaron Averett Avatar answered Nov 09 '22 23:11

Aaron Averett


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>
like image 24
commonpike Avatar answered Nov 09 '22 23:11

commonpike