2017-10-10 164 views
3

我想检查数组是否包含对象。我不想比较值,只是想检查我的数组中是否存在对象?如何检查数组是否至少包含一个对象?

Ex。

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

所以,我怎样才能检查,如果数组包含对象

+0

将它永远是ID?或者它可以改变? – shv22

+0

循环访问数组项并测试它是否是对象https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript –

+0

你在寻找一个特定的值,或者只是如果数组包含“任何对象”? – Cerbrus

回答

5

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

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

+0

谢谢@ Alexandru-Ionut Mihai。你的答案是完美的。你能告诉我这是如何工作的吗? – parth

+0

@parth,'some'方法为数组中的任何项目提供回调测试函数。 'test'函数检查数组项是否是对象。如果'typeof a'是object,'condition'就是如果'typeof a'是object.'some'方法返回true,如果从数组中至少有一个条目满足条件。 –

+0

明白了。谢谢。 – parth

4

我要检查,如果数组包含对象或不

使用some简单地检查阵列中的任何项目都有类型“对象”的值

var hasObject = $arr.some(function(val){ 
    return typeof val == "object"; 
}); 
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

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

相关问题