Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 258
Alexis Avatar asked Mar 26 '13 05:03

Alexis


People also ask

How do you count the number of keys in an object?

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.

How do you count the number of keys in a JSON object?

USE len() TO COUNT THE ITEMS IN A JSON OBJECT. Call len(obj) to return the number of items in a JSON object obj.

How will you find out the numbers of properties in an object?

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.

How do I count the number of objects in JavaScript?

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.


2 Answers

Object.keys(obj).length

It should work the same way in coffeescript

see example

like image 111
mpm Avatar answered Oct 23 '22 02:10

mpm


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

like image 37
jondavidjohn Avatar answered Oct 23 '22 02:10

jondavidjohn