parth
parth

Reputation: 674

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

Upvotes: 17

Views: 32775

Answers (5)

Gorky
Gorky

Reputation: 1413

With a type check on array

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

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48327

You can use some method which tests whether at least one element in the array passes the test implemented by the provided function.

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

Upvotes: 26

William Valhakis
William Valhakis

Reputation: 370

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386519

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

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68363

I want to check if array contains object or not

Use some to simply check if any item of the array has value of type "object"

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

Upvotes: 5

Related Questions