Chains and Flattened Arrays
Using Lodash, we can flatten complex array structures into a single array, and then remove duplicates. Chains simplify the whole process.
by Adam Boduch
HTML
<h3>Flattened Actions</h3>
<ul id="flattened"></ul>
JavaScript
var data = [
{
name: "Item 1",
actions: [ "Create", "Read", "Delete" ]
},
{
name: "Item 2",
actions: [ "Create", "Update", "Delete" ]
},
{
name: "Item 3",
actions: [ "Delete" ]
}
];
// Four things happen here:
// 1. Build the chainable data object.
// 2. Build the flattend array.
// 3. Remove deplicate values.
// 4. Assign resulting object to "actions".
var actions = _.chain( data )
.flatten( "actions" )
.uniq();
// The DOM action list.
var list = document.getElementById( "flattened" );
// The chain object is iterable.
actions.each( function( action ) {
var item = document.createElement( "li" );
item.appendChild( document.createTextNode( action ) );
list.appendChild( item );
});