I want to check if an array contains only objects. So I created this function:
function arrayContainsObjOnly(arr){
return arr.join("").replace(/\[object Object\]/g, "") === "";
}
Here is how you would use it:
// return true
arrayContainsObjOnly([
{"name" : "juan", "age" : 28},
{"name" : "pedro", "age" : 25}
]);
// return false
arrayContainsObjOnly([
{"name" : "juan", "age" : 28},
"name=pedro;age=25"
]);
Is there any cleaner way to do this? Is using the literal "[object Object]" for checking is safe?
I also prefer a non-jQuery solution.
Conceptually simpler and cleaner, but no less code:
function arrContainsObjOnly(arr) {
return arr.every(function(el) {
return Object.prototype.toString.call(el) === '[object Object]';
});
}
Update
On second thought, this variant would be better, as it would return false on encountering the first non-object:
function arrContainsObjOnly(arr) {
return !arr.some(function(el) {
return Object.prototype.toString.call(el) !== '[object Object]';
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With