admin管理员组

文章数量:1391987

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

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

Share Improve this question asked Jul 29, 2012 at 14:57 bodokaiserbodokaiser 15.8k27 gold badges100 silver badges143 bronze badges 1
  • Take a look at this answer: stackoverflow./a/4929935/950890 – Fredrik Sundmyhr Commented Jul 29, 2012 at 15:03
Add a ment  | 

2 Answers 2

Reset to default 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" });

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/#

本文标签: javascriptUnderscore Wrap array with collection methodsStack Overflow