CoffeeScript - list comprehensions



In CoffeeScript, we can also store a group of objects in an array. The list comprehensions are used to map an array of objects to another array.

Syntax

Suppose we have an array of objects in CoffeeScript as [{key1: "value", key2: value}, {key1: "value", key2: value}] then you can iterate these elements using the list comprehension as shown below.

for key,value of  [ {key1: "value", key2: value}, {key1: "value", key2: value} ]
   console.log key+"::"+value

Example

The following example demonstrates the usage of the list comprehension provided by CoffeeScript. Save this code in a file with name list_comprehensions.coffee

students =[  
    name: "Mohammed" 
    age: 24
    phone: 9848022338 
  ,  
    name: "Ram" 
    age: 25
    phone: 9800000000 
  ,  
    name: "Ram" 
    age: 25
    phone: 9800000000   
 ]  
 
names = (student.name for student in students)
console.log names

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c list_comprehensions.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var names, student, students;

  students = [
    {
      name: "Mohammed",
      age: 24,
      phone: 9848022338
    }, {
      name: "Ram",
      age: 25,
      phone: 9800000000
    }, {
      name: "Ram",
      age: 25,
      phone: 9800000000
    }
  ];

  names = (function() {
    var i, len, results;
    results = [];
    for (i = 0, len = students.length; i < len; i++) {
      student = students[i];
      results.push(student.name);
    }
    return results;
  })();

  console.log(names);

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> list_comprehensions.coffee

On executing, the CoffeeScript file produces the following output.

[ 'Mohammed', 'Ram', 'Ram' ] 
coffeescript_comprehensions.htm
Advertisements