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
2 Answers
Reset to default 7For 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
版权声明:本文标题:javascript - Underscore: Wrap array with collection methods - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744673023a2618941.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论