[英]How to check if array contains at least one object ?
I want to check if array contains object or not. 我想检查数组是否包含对象。 I am not trying to compare values just want to check in my array if object is present or not?
如果对象存在与否,我不想比较值只是想检查我的数组?
Ex. 防爆。
$arr = ['a','b','c'] // normal
$arr = [{ id: 1}, {id: 2}] // array of objects
$arr = [{id: 1}, {id:2}, 'a', 'b'] // mix values
So how can i check if array contains object 那么如何检查数组是否包含对象
You can use some
method which tests whether at least one element in the array
passes the test
implemented by the provided function. 您可以使用
some
方法来测试array
是否至少有一个元素通过了由提供的函数实现的test
。
let arr = [{id: 1}, {id:2}, 'a', 'b']; let exists = arr.some(a => typeof a == 'object'); console.log(exists);
var hasObject = function(arr) { for (var i=0; i<arr.length; i++) { if (typeof arr[i] == 'object') { return true; } } return false; }; console.log(hasObject(['a','b','c'])); console.log(hasObject([{ id: 1}, {id: 2}])); console.log(hasObject([{id: 1}, {id:2}, 'a', 'b']));
You could count the objects and use it for one of the three types to return. 您可以计算对象并将其用于返回的三种类型之一。
function getType(array) { var count = array.reduce(function (r, a) { return r + (typeof a === 'object'); }, 0); return count === array.length ? 'array of objects' : count ? 'mix values' : 'normal'; } console.log([ ['a', 'b', 'c'], [{ id: 1 }, { id: 2 }], [{ id: 1 }, { id: 2 }, 'a', 'b'] ].map(getType));
对数组进行类型检查
const hasObject = a => Array.isArray(a) && a.some(val => typeof val === 'object')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.