【问题标题】:How to check if array contains at least one object ?如何检查数组是否包含至少一个对象?
【发布时间】:2018-03-21 15:58:00
【问题描述】:

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

例如

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

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

【问题讨论】:

  • 会一直是 id 吗?还是可以改变?
  • 遍历数组项并测试它是否是对象stackoverflow.com/questions/8511281/…
  • 您是在寻找特定的值,还是仅仅在数组包含“任何对象”时?
  • @shv22 .object 可以是任何东西
  • @Cerbrus 只想检查数组是否包含对象。

标签: javascript arrays node.js


【解决方案1】:

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

使用some 简单地检查数组中的任何项是否具有“对象”类型的值

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢@Alexandru-Ionut Mihai。你的答案很完美。你能告诉我这是如何工作的吗?
    • @parth, some 方法为数组中的任何项目提供回调测试函数。 test 函数检查数组项是否为对象。 condition 是如果 typeof a 是对象。some 方法返回 true 如果 at least 数组中的一项满足条件。
    • 知道了。谢谢。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        对数组进行类型检查

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-04-28
          • 2018-08-11
          • 2018-04-18
          • 1970-01-01
          • 2015-07-23
          • 1970-01-01
          • 2012-08-05
          相关资源
          最近更新 更多