Make sure array contains element-only object in Javascript
I want to check if an array only contains objects. So I created this function:
function arrayContainsObjOnly(arr){
return arr.join("").replace(/\[object Object\]/g, "") === "";
}
This is how you 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 a cleaner way to do this? Uses a literal "[object Object]"
for security checks? I also prefer a non-jQuery solution.
+3
source to share
2 answers
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 the other hand, this option would be better, as it would return false
on collision with the first non-object:
function arrContainsObjOnly(arr) {
return !arr.some(function(el) {
return Object.prototype.toString.call(el) !== '[object Object]';
});
}
+1
source to share
you can use the typeof operator
try this
// CASE 1 :
var arrItem = [
{"name" : "juan", "age" : 28},
{"name" : "pedro", "age" : 25},
"name=pedro,age=25"
]
var boolIsAllContainObject = arrItem.every(function(oneItem,key){
if ((typeof oneItem) === "object") {
return true;
} else {
return false;
}
});
console.log(boolIsAllContainObject) //return false as one element is not object
// CASE 2:
var arrItem = [
{"name" : "juan", "age" : 28},
{"name" : "pedro", "age" : 25},
{"name" : "name=pedro,age=25"}
]
var boolIsAllContainObject = arrItem.every(function(oneItem,key){
if ((typeof oneItem) === "object") {
return true;
} else {
return false;
}
});
console.log(boolIsAllContainObject) //return true allelement are object
0
source to share