Underscore CLI is a powerful command-line utility that allows developers to process text and data, particularly JSON, using familiar lodash-style syntax. This tool streamlines common data manipulation tasks directly from your terminal, making it an invaluable asset for scripting, automation, and quick data analysis.
The primary function of Underscore CLI is to apply lodash functions to input data, typically JSON. Below are several examples demonstrating its versatility:
You can transform JSON input by selecting and mapping properties. This is useful for extracting specific data points or restructuring JSON objects.
# Transform JSON input using lodash-style syntax
underscore select 'map(array, "property")' < input.json
Underscore CLI excels at filtering JSON arrays based on specific criteria, allowing you to isolate relevant data.
# Apply lodash functions on a JSON array
underscore select 'filter(array, { "active": true })' < input.json
Easily sort JSON arrays by a particular property value, which is crucial for ordered data presentation.
# Sorting a JSON array by a property value
underscore select 'sortBy(array, "age")' < input.json
Select only the desired properties from objects within a JSON array, simplifying complex data structures.
# Pick specific properties from objects in a JSON array
underscore select 'map(array, pick(["name", "age"]))' < input.json
Perform aggregations like summing values across a JSON array using the reduce function.
# Summarize values in a JSON array
underscore select 'reduce(array, (sum, n) => sum + n.value, 0)' < input.json
Group elements of a JSON array based on a common property, creating categorized datasets.
# Group elements of a JSON array by a property
underscore select 'groupBy(array, "category")' < input.json
Count elements within a collection based on a specified condition, providing valuable statistical insights.
# Count elements in a collection based on a condition
underscore select 'countBy(array, item => item.completed ? "completed" : "pending")' < input.json
Extract a single property from each object in a JSON array to create a simple list of values.
# Pluck a single property from each object in a JSON array
underscore select 'pluck(array, "name")' < input.json
Locate a specific object within a JSON array that matches a given condition.
# Find an object in a JSON array based on a condition
underscore select 'find(array, { "id": 1 })' < input.json
Clean up arrays by removing falsy values (e.g., null, undefined, false, 0, "").
# Remove falsy values from a JSON array
underscore select 'compact(array)' < input.json
For more advanced usage and a deeper understanding of lodash functions, refer to the official lodash documentation: