How to check if array contains at least one object ?

前端 未结 5 1793
余生分开走
余生分开走 2021-02-08 13:04

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 =         


        
5条回答
  •  悲&欢浪女
    2021-02-08 13:40

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

提交回复
热议问题