Skip to content

Instantly share code, notes, and snippets.

@kpuputti
Created September 27, 2012 11:39
Show Gist options
  • Save kpuputti/3793564 to your computer and use it in GitHub Desktop.
Save kpuputti/3793564 to your computer and use it in GitHub Desktop.
Flattenezmagic
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