Number of keys in an object with Coffeescript

I would like to know how many keys are in my coffeescript object.

I can do it with js:

Object.keys(obj).length

Is there a way to do this in Coffeescript?

+7
source share
3 answers
 Object.keys(obj).length 

It should work the same in coffeescript

see example

+13
source

If you are concerned about outdated browser support

 Object.keys(obj).length 

is an ECMAScript 5 solution

However, if you want to support IE8 before, this is a pretty unobtrusive Coffeescript solution

 (k for own k of obj).length 

It uses CoffeeScript Syntax of understanding to create an array of keys.

 keys = (k for own k of obj) # Array of keys from obj 

And then calls the length in this array

Compiled JavaScript Example

+9
source

I create a prototype function d keys :

 Object.defineProperty Object.prototype, 'keys', enumerable : false, writable : true, value: -> return (key for own key of @) 

so that I can just use it like that

 nodes_Ids: -> return _nodes_By_Id.keys() 

which is used in this test

 it 'add_Node',-> visGraph = Vis_Graph.ctor() visGraph.add_Node('a' ).nodes.assert_Size_Is(1) visGraph.add_Node('a' ).nodes.assert_Size_Is(1) visGraph.add_Node( ).nodes.assert_Size_Is(1) visGraph.add_Node(null).nodes.assert_Size_Is(1) visGraph.add_Node('b' ).nodes.assert_Size_Is(2) visGraph.nodes_Ids() .assert_Contains ('a' ) visGraph.nodes_Ids() .assert_Contains ('b') visGraph.nodes_Ids() .assert_Not_Contains ('c' ) 
0
source

All Articles