Thursday, 29 August 2013

How to break an array of objects into 2 arrays, using Underscore/LoDash

How to break an array of objects into 2 arrays, using Underscore/LoDash

I have an array of objects:
var arr = [
{field1: value, field2: value, field3: value, field4: value},
{field1: value, field2: value, field3: value, field4: value},
{field1: value, field2: value, field3: value, field4: value}
];
I need to break it into 2 arrays of objects: one containing objects that
have only field1 and field 3, and one containing objects that have all the
rest. I'm trying to use Underscore (well, actually LoDash - but they're
the same) and so far, all I got is:
var arr1 = [], arr2 = [];
_.forEach(arr, function(line) {
arr1.push(_.pick(line, ['field1', 'field3']));
arr2.push(_.omit(line, ['field1', 'field3']));
});
While this code works it strikes me as very inefficient. I'm sure I'm
missing an Underscore function that can make my life easier, my code more
readable, and my program more efficient.

No comments:

Post a Comment