How can test over an object like the array.every() method? Trying to detect if all the terms in a query object are blank before sending it on. Obviously I could just write a little routine in a for loop, but I'm expecting there's a more succinct way of acplishing this.
// array - works
var queryArr = [ "", "" ];
if(!queryArr.every(function(el, i, arr) { return el == "" } )) {
alert("nothing to search");
}
// object - "undefined is not a function"
var queryObj = { term1: "", term2: "" };
if(!queryObj.every(function(el, i, arr) { return el == "" } )) {
alert("nothing to search");
}
How can test over an object like the array.every() method? Trying to detect if all the terms in a query object are blank before sending it on. Obviously I could just write a little routine in a for loop, but I'm expecting there's a more succinct way of acplishing this.
// array - works
var queryArr = [ "", "" ];
if(!queryArr.every(function(el, i, arr) { return el == "" } )) {
alert("nothing to search");
}
// object - "undefined is not a function"
var queryObj = { term1: "", term2: "" };
if(!queryObj.every(function(el, i, arr) { return el == "" } )) {
alert("nothing to search");
}
Share
Improve this question
asked Oct 31, 2014 at 19:41
robisrobrobisrob
96012 silver badges24 bronze badges
2
- for in loop is the best – guramidev Commented Oct 31, 2014 at 19:45
- There is no built in function, but it is easy to make one. – Karl-André Gagnon Commented Oct 31, 2014 at 19:53
2 Answers
Reset to default 1Map can be used call a function on each object in an array.
http://api.jquery./jquery.map/
You could implement your own every method this way:
Object.prototype.every=function(evalFunction){
var self=this,
property;
if(typeof evalFunction!=='function')
return evalFunction;
for(property in self){
if(self.hasOwnProperty(property) && !evalFunction(self[property], property, self)){
return false;
}
}
return true;
}
Then you could use the new every method on objects the same way you do with arrays
But if you only want to test this once on your code I sugest to use for in loop or robisrob's map solution