如何检查数组中是否至少包含一个对象?

16

我想检查数组中是否包含对象。我不想比较值,只是想检查我的数组中是否存在该对象。

例如:

$arr = ['a','b','c'] // normal
$arr = [{ id: 1}, {id: 2}] // array of objects
$arr = [{id: 1}, {id:2}, 'a', 'b'] // mix values

那么我应该如何检查数组是否包含对象


它会一直是id吗?还是可能会改变? - shv22
循环遍历数组项并测试其是否为对象。https://dev59.com/S2oy5IYBdhLWcg3wfeMR - Zamrony P. Juhara
你是在寻找特定的值,还是只是想知道数组是否包含“任何对象”? - Cerbrus
@shv22 .object 可以是任何东西。 - parth
@Cerbrus 只是想检查数组是否包含一个对象。 - parth
5个回答

25

您可以使用some方法,该方法测试数组中是否有至少一个元素通过提供的函数实现的测试

let arr = [{id: 1}, {id:2}, 'a', 'b'];
let exists = arr.some(a => typeof a == 'object');
console.log(exists);


@parth,“some”方法为数组中的每个元素提供了回调测试函数。test函数检查数组项是否为对象。 condition是指如果typeof a是对象,则条件为满足。如果至少有一个数组项满足该条件,则some方法返回true。 - Mihai Alexandru-Ionut

5

我想检查数组是否包含对象

使用some方法来简单地检查数组中的任何一项是否具有“object”类型的值。

var hasObject = $arr.some( function(val){
   return typeof val == "object";
});

1

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']));


0
你可以计算对象并将其用于返回三种类型之一。

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));


0

对数组进行类型检查

const hasObject = a => Array.isArray(a) && a.some(val => typeof val === 'object')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接