Created
September 27, 2012 11:39
-
-
Save kpuputti/3793564 to your computer and use it in GitHub Desktop.
Flattenezmagic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = [ | |
{ name: 'a', other: 'ignore me', sub: [{name: 'a1'}, {name: 'a2'}] }, | |
{ name: 'b', sub: [{name: 'b1'}, {name: 'b2', another: 'ignore me too'}] } | |
]; | |
// Wanted: ['a', 'a1', 'a2', 'b', 'b1', 'b2'] | |
// Flattenezify! | |
_.chain(data).map(function (d) { | |
return [d.name].concat(_.pluck(d.sub, 'name')); | |
}).flatten().value() | |
// Ok, but what if sub can be null? | |
var data = [ | |
{ name: 'a', other: 'ignore me', sub: [{name: 'a1'}, {name: 'a2'}] }, | |
{ name: 'b', sub: [{name: 'b1'}, {name: 'b2', another: 'ignore me too'}}] }, | |
{ name: 'c', sub: null }, | |
]; | |
// Wanted: ['a', 'a1', 'a2', 'b', 'b1', 'b2', 'c'] | |
_.chain(data).map(function (d) { | |
return [d.name].concat(d.sub ? _.pluck(d.sub, 'name') : []); | |
}).flatten().value() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment