1

I have an array full of objects:

var myArray = [{ "user": "anton" }, { "user": "joe" }];

I would now like to wrap the array into a Underscore Collection object so that I can nativly use underscore's collection methods (remove, add) with it:

myArray = _(myArray); // this only add object methods
myArray.add({ "user": "paul" });

So how do I wrap an array with underscore to use underscores collection methods

bodokaiser
  • 13,492
  • 20
  • 90
  • 133

2 Answers2

7

For the record since the accepted answer is missleading:

Underscore used as a function, will wrap its argument, i.e.

_([a, b, c])

is equivalent to:

_.chain([a, b, c])

In fact chain is defined as:

_.chain = function(obj) {
  return _(obj).chain();
};

Now to your question:

You confuse Backbone which provides Collections, with Underscore which does not. Backbone collections can be easily initialized from an array, for example:

var c = new Backbone.Collection([{ "user": "anton" }, { "user": "joe" }]);

will work just fine. You can further do:

c.add({ "user": "paul" });
ggozad
  • 13,009
  • 3
  • 38
  • 49
2

Generally underscore api doesn't wrap array or object. just passing it first argument. ex)

_.first([5, 4, 3, 2, 1]); //Note first argument
=> 5
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

But chain (_.chain(obj)) Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is used.

var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
var youngest = _.chain(stooges)
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  .first()
  .value();
=> "moe is 21"

check underscore api : http://underscorejs.org/#

Chris Pfohl
  • 15,337
  • 8
  • 60
  • 104
Hacker Wins
  • 1,219
  • 9
  • 19