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?
keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.
USE len() TO COUNT THE ITEMS IN A JSON OBJECT. Call len(obj) to return the number of items in a JSON object obj.
Use the Object. keys() method, passing the object you want to inspect, to get an array of all the (own) enumerable properties of the object.
A JavaScript for loop will iterate through all the linked properties of the object. To count the object's own enumerable properties, you may consider using another approach, Object. keys(), which only enumerates the object's own enumerable properties.
Object.keys(obj).length
It should work the same way in coffeescript
see example
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With