Take this:
has_competitors:function(){
var c = false;
_.each(this.competitors, function(obj, index){ // lodash here
if(obj.name && obj.name.trim() !== ''){
c = true;
return false; // to break the loop
}
});
return c;
}
I don't like the form of this, but till now I didn't find a more concise way. Could you suggest a better way? :) I mean, less lines.
2 Answers 2
I assume you are using lodash library.
You may use _.some function.
Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy. The predicate is invoked with three arguments: (value, index|key, collection).
has_competitors: function(){
return _.some(this.competitors, function(obj){
return obj.name && obj.name.trim() !== '';
};
}
- Since ES5 (which all browsers support nowadays) is
array.some()
. It works in the same way as Lodash's/Underscore's_.some()
but without the library. - If you target ES6, you can further trim your code using shorthand object methods and arrow functions.
- Your
object.trim()
can blow up ifobject.name
is truthy but not a string. Do atypeof obj.name === 'string'
instead of a truthy check. If it is always guaranteed to be a string, the truthy check is redundant since a trimmed empty string will always be empty.
So your code could be as simple as:
has_competitors(){
return this.competitors.some(obj => obj.name.trim() !== '')
}
-
\$\begingroup\$ Good suggestions. Anyway in my case competitors is a collection (obj) not an array, so I'll go for lodash. \$\endgroup\$Luca Reghellin– Luca Reghellin2018年07月26日 07:50:59 +00:00Commented Jul 26, 2018 at 7:50
_
is — use the lodash.js or underscore.js tag as appropriate. \$\endgroup\$