Alexis
Alexis

Reputation: 25203

Count number of keys in object with Coffeescript

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

I can do it with this in js:

Object.keys(obj).length

Is there a way to do this in Coffeescript?

Upvotes: 7

Views: 8552

Answers (3)

Dinis Cruz
Dinis Cruz

Reputation: 4289

I create thed keys prototype function:

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

so that I can just use it like this

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' )

Upvotes: 0

jondavidjohn
jondavidjohn

Reputation: 62402

If you are worried about legacy browser support

Object.keys(obj).length

is an ECMAScript 5 Solution

However if you are wanting to support IE8 and earlier this is a fairly unobtrusive Coffeescript specific solution

(k for own k of obj).length

This utilizes CoffeeScript's Comprehension Syntax to build an array of keys

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

And then calls length on that array

Example with compiled JavaScript

Upvotes: 10

mpm
mpm

Reputation: 20155

Object.keys(obj).length

It should work the same way in coffeescript

see example

Upvotes: 13

Related Questions