Introduction to linq.js by Example

11 Jul 2017 21:09
Tags enumerable linq

Back to list of posts

Overview

linq.js is a JavaScript version of .NET's LINQ to Objects that can be used to query and manipulate an Array, Object, NodeList, Number, or String. It implements all the .NET methods as well as many extra methods. This article will focus on the common functions that can be applied to Arrays of JSON objects.

Enumerable

The linq.js library contains an Enumerable object that provides methods used to apply declarative code that describes what you want to retrieve. Each method returns the Enumerable object so that functions can be chained together. The declarative code can be applied in one of 3 formats:

  1. Function - a function that has a parameter that is the object from the array that is being evaluated.
  2. Lambda Expression - a string containing a Lambda Expression identical in syntax to a .NET Lambda Expression.
  3. $ string - a string that (for lack of a better description) applies the declarative code to the current object as expressed by a dollar sign ($).

From

The first step to defining an Enumerable expression is to provide the Enumerable object with the Array of JSON objects to be manipulated. Here is an example:

// An array of employees.
var employees = [
    { firstName: "John", lastName: "Doe", role: "Developer", rating: 4 }, 
    { firstName: "Jane", lastName: "Smith", role: "Manager", rating: 3 }
];

// Initialize the Enumerable object.
var enumerable = Enumerable.From(employees);

Select

The Select method is used to manipulate each object in the array and return it in a new form. The Enumerable.ToArray method is used to execute the declarative and return the results as an Array of JSON objects.

Here is an example:

// An array of employees.
var employees = [
    { firstName: "John", lastName: "Doe", role: "Developer", rating: 4 }, 
    { firstName: "Jane", lastName: "Smith", role: "Manager", rating: 3 }
];
 
// Function example.
var names = Enumerable.From(employees)
    .Select(function (employee) {
        return { name: employee.firstName + ' ' + employee.lastName };
    })
    .ToArray();
 
// Lambda Expression example:
var names = Enumerable.From(employees)
    .Select("employee => { name: employee.firstName + ' ' + employee.lastName }")
    .ToArray();
 
// "$ string" example:
var names = Enumerable.From(employees)
    .Select("{ name: $.firstName + ' ' + $.lastName }")
    .ToArray();
 
// Results.
// [{ name: "John Doe" }, { name: "Jane Smith" }]

Where

The Where method filters the objects in the array by returning a boolean to indicate whether the object should be included in the results.

Here is an example:

// An array of employees.
var employees = [
    { firstName: "John", lastName: "Doe", role: "Developer", rating: 4 }, 
    { firstName: "Jane", lastName: "Smith", role: "Manager", rating: 3 }
];
 
// Function example.
var names = Enumerable.From(employees)
    .Where(function (employee) {
        return employee.role === "Developer";
    })
    .Select(function (employee) {
        return { name: employee.firstName + ' ' + employee.lastName };
    })
    .ToArray();
 
// Lambda Expression example:
var names = Enumerable.From(employees)
    .Where("employee => employee.role === 'Developer'")
    .Select("employee => { name: employee.firstName + ' ' + employee.lastName }")
    .ToArray();
 
// "$ string" example:
var names = Enumerable.From(employees)
    .Where("$.role === 'Developer'")
    .Select("{ name: $.firstName + ' ' + $.lastName }")
    .ToArray();
 
// Results.
// [{ name: "John Doe" }]

OrderBy and OrderByDescending

The OrderBy and OrderByDescending methods order the objects in the array.

Here is an example:

// An array of employees.
var employees = [
    { firstName: "John", lastName: "Doe", role: "Developer", rating: 4 }, 
    { firstName: "Jane", lastName: "Smith", role: "Manager", rating: 3 }
];
 
// Function example.
var orderedList = Enumerable.From(employees)
    .OrderBy(function (employee) {
        return employee.firstName;
    })
    .ToArray();
 
// Lambda Expression example:
var orderedList = Enumerable.From(employees)
    .OrderBy("employee => employee.firstName")
    .ToArray();
 
// "$ string" example:
var orderedList = Enumerable.From(employees)
    .OrderBy("$.firstName")
    .ToArray();
 
// Results.
// [{ firstName: "Jane", lastName: "Smith", role: "Manager", rating: 3 }, { firstName: "John", lastName: "Doe", role: "Developer", rating: 4 }]

ForEach

Loop over each object in the array.

Here is an example:

var employees = [
    { firstName: "John", lastName: "Doe", role: "Developer" }, 
    { firstName: "Jane", lastName: "Smith", role: "Manager" }
];
 
// Using function as a parameter.
Enumerable.From(employees)
    .ForEach(function (employee) { console.log(employee); });
 
// Using a "Lambda-style" string as the parameter.
Enumerable.From(employees)
    .ForEach("employee => console.log(employee)");
 
// Using a string as the parameter.
Enumerable.From(employees)
    .ForEach("console.log($)");

GroupBy

The GroupBy method is a bit more complicated. It takes 3 parameters. They are:

  1. The first parameter identifies the attribute that is used to group the elements. To group the employees provided in the examples by role, the first parameter would identify the role attribute.
  2. The second parameter identifies what value(s) will be included in each group. For example, when grouping the employees by role, the values included in each group may be firstName and lastName.
  3. The third parameter creates the result value for each group and it's key. For example, when grouping the employees by role, the array of values for each group could be assigned to a member attribute.

Here is an example:

var employees = [
    { firstName: "John", lastName: "Doe", role: "Developer" }, 
    { firstName: "Jane", lastName: "Smith", role: "Manager" }
];
 
// Using functions as parameters.
var teams = Enumerable.From(employees)
    .GroupBy(
        function (employee) { return employee.role; }, 
        function (employee) { return { name: employee.firstName + ' ' + employee.lastName }; }, 
        function (key, grouping) { return { team: key, members: grouping.source }; }
    )
    .ToArray();
 
// Using "Lambda-style" strings as the parameter.
var teams = Enumerable.From(employees)
    .GroupBy(
        "employee => employee.role", 
        "employee => { name: employee.firstName + ' ' + employee.lastName }", 
        "key, grouping => { team: key, members: grouping.source }"
    )
    .ToArray();
 
// Using strings as parameters.
var teams = Enumerable.From(employees)
    .GroupBy(
        "$.role", 
        "{ name: $.firstName + ' ' + $.lastName }", 
        "{ role: $, people: $$.source }"
    )
    .ToArray()
 
// Results.
// [{
//      team: "Developer",
//     members: [{ name: "John Doe" }]
// },{
//      team: "Manager",
//      members: [{ name: "Jane Smith" }]
// }];

Aggregates

linq.js contains the following aggregate methods:

  1. Average
  2. Count
  3. Max
  4. Min
  5. MaxBy
  6. MinBy
  7. Sum

Here is an example of Average:

var employees = [
    { firstName: "John", lastName: "Doe", role: "Developer", rating: 4 }, 
    { firstName: "Jane", lastName: "Smith", role: "Manager", rating: 3 }
];
 
// Using function as a parameter.
var average = Enumerable.From(employees).Average(function (employee) { return employee.rating; });
 
// Using a "Lambda-style" string as the parameter.
var average = Enumerable.From(employees).Average("employee => employee.rating");
 
// Using a string as the parameter.
var average = Enumerable.From(employees).Average("$.rating");
 
// Results.
// average === 3.5;

References

Comments: 0

Add a New Comment

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License