Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

javascript - underscore contains (_.contains) on object types

I'm just getting started with Javascript and using the Underscore library. I see they have all sorts of utility function, like _.contains. Is there a way to make this work on objects?

var indexes = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'},  {'id': 9, 'name': 'nick'}, {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'} ];

if (_.contains(indexes, {'id':1, 'name': 'jake'})) {
    console.log("contains");
}

Most of the examples they show have simple arrays with strings or numbers in them. I was wondering what I can do to use their utility functions like _.contains for objects. Thanks.

question from:https://stackoverflow.com/questions/15869648/underscore-contains-contains-on-object-types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

contains requires the values to be comparable with === which will not work with different instances of objects.

For instance it would work if you passed the exact object you are searching for, which isn't very useful.

if (_.contains(indexes, indexes[0])) {

You can however use where or findWhere.

if (_.findWhere(indexes, {'id':1, 'name': 'jake'})) {

findWhere is new in Underscore 1.4.4 so if you do not have it, you can use where.

if (_.where(indexes, {'id':1, 'name': 'jake'}).length > 0) {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...