【问题标题】:a better way to loop through an array of items一种更好的方法来遍历一组项目
【发布时间】:2021-01-26 13:42:21
【问题描述】:

我的模型如下所示

this.Model

Model {class: undefined items: Array(0) tag: undefined launch: undefined length: undefined name: undefined Id: "de4d704a-b754-4546-b3ab-f0c131eba84a" time: "15:36" tonnage: undefined}

模型中唯一始终具有值的对象是 Id 和 Time。

我有一个 if 语句遍历我的每个对象以检查其是否为空,如下所示:

    if ( this.Model.class == null && this.Model.name == null && this.Model.tag== null && this.Model.launch == null && this.Model.length == null && this.Model.tonnage == null && this.Model.items.length == 0) 
                {
                    //does something in here
                }

所以我想检查除时间和 ID 之外的所有对象是否为空,有没有比我在 if 语句中使用上述方法更好的方法?

【问题讨论】:

    标签: javascript arrays typescript


    【解决方案1】:

    我会创建一个函数来使用Object.entriesArray.every 来检查。

    此解决方案的好处:

    • 可重复使用的实用函数。
    • 可与任意数量的键一起忽略。
    • 如果您指定要忽略的键不是所提供对象的一部分,则函数的键入将引发错误。

    Playground in TypeScript


    Javascript 中的片段。

    function checkAllKeysExceptGivenKeysToBeNullable(obj, keys) {
      return Object.entries(obj).every(([
        key,
        value,
      ]) => {
        // If the key has to be ignored
        if (keys.includes(key)) {
          return true;
        }
    
        // Check the value to be nullable
        return value === null ||
          value === void 0 ||
          (value instanceof Array && value.length === 0);
      });
    }
    
    console.log(checkAllKeysExceptGivenKeysToBeNullable({
      class: undefined,
      items: Array(0),
      tag: undefined,
      launch: undefined,
      length: undefined,
      name: undefined,
      Id: 'de4d704a-b754-4546-b3ab-f0c131eba84a',
      time: '15:36',
      tonnage: undefined,
    }, [
      'Id',
      'time',
    ]));
    
    console.log(checkAllKeysExceptGivenKeysToBeNullable({
      class: undefined,
      items: Array(0),
      tag: 'nope',
      launch: undefined,
      length: undefined,
      name: undefined,
      Id: 'de4d704a-b754-4546-b3ab-f0c131eba84a',
      time: '15:36',
      tonnage: undefined,
    }, [
      'Id',
      'time',
    ]));

    function checkAllKeysExceptGivenKeysToBeNullable<T extends {
      [key in keyof T]: null | undefined | Array<unknown> | unknown;
    }>(obj: T, keys: (keyof T)[]): boolean {
      return Object.entries(obj).every(([
        key,
        value,
      ]) => {
        if (keys.includes(key as keyof T)) {
          return true;
        }
    
        return value === null ||
               value === void 0 ||
               (value instanceof Array && value.length === 0);
      });
    }
    
    console.log(checkAllKeysExceptGivenKeysToBeNullable({
      class: undefined,
      items: Array(0),
      tag: undefined,
      launch: undefined,
      length: undefined,
      name: undefined,
      Id: 'de4d704a-b754-4546-b3ab-f0c131eba84a',
      time: '15:36',
      tonnage: undefined,
    }, [
      'Id',
      'time',
    ]));
    
    console.log(checkAllKeysExceptGivenKeysToBeNullable({
      class: undefined,
      items: Array(0),
      tag: 'nope',
      launch: undefined,
      length: undefined,
      name: undefined,
      Id: 'de4d704a-b754-4546-b3ab-f0c131eba84a',
      time: '15:36',
      tonnage: undefined,
    }, [
      'Id',
      'time',
    ]));
    

    【讨论】:

    • 我有一个简单的问题,因为我有存储值的“this.model”。当我调用 this.checkAllExceptGivenKeysToBeNullable() 函数时。我如何将 this.model 实例传递给它?
    • 例子:如果model是A类的一个属性,如果你把checkAllExceptGivenKeysToBeNullable放在A里面,你可以叫它this.checkAllExceptGivenKeysToBeNullable(this.model, [ 'Id', 'time' ])
    • 例子:如果model是A类的一个属性。如果你把checkAllExceptGivenKeysToBeNullable放在一个叫B的实用程序类中作为一个静态方法,你可以把它称为B.checkAllExceptGivenKeysToBeNullable(this.model, [ 'Id', 'time' ])
    【解决方案2】:

    玩了一会儿,我想出了一个使用Object.keys()的解决方案

    /**
     * Checks if all of the objects values are null, except for keys in param except
     * @param obj: The object to test
     * @param except (optional): keys to omit the null check on
     */
    function checkIfPropertiesNull(obj: {[key: string]: unknown}, except: string[] = []): boolean {
       const keys = Object.keys(obj).filter(key => !except.includes(key));
       for(const key of keys){
           if(obj[key] !== null){
               return false;
           }
       }
       return true;
    }
    
    
    console.log(checkIfPropertiesNull({ id: 1, name: 'mike', city: null }, ['id', 'name'])); // true, because id and name are not checked
    console.log(checkIfPropertiesNull({ id: 1, name: 'mike', city: 'Munich' }, ['id', 'name'])); // false, city isn't null
    

    Playground

    【讨论】:

      【解决方案3】:
      for (let prop in Modal) {
          if (Modal.prop != time && Modal.prop != id && Modal[prop] != null) {
              return false
          }
          
      }
      return true
      

      如果除了 ID 和 Time 之外的所有属性都为空,则返回 true。

      【讨论】:

        【解决方案4】:

        好吧,在这种情况下你有两个选择:

        1. 将您的循环放在一个函数中,以将此逻辑与您的模型分开:
        function checkProperties(obj) {
            for (var key in obj) {
                if (obj[key] !== null && obj[key] != "")
                    return false;
            }
            return true;
        }
        
        var obj = {
            x: null,
            y: "",
            z: 1
        }
        
        checkProperties(obj) //returns false
        
        1. 使用 Object.values 和 every 来检查你的属性作为一个数组。
        let report = {
          property1: null,
          property2: null,
        }
        
        let result = !Object.values(report).every(o => o === null);
        
        console.log(result);
        

        【讨论】:

        • 提供答案而不是重定向到链接通常很有用。如果您认为此问题与现有问题重复,您可以随时使用评论进行通知。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-19
        • 2011-03-10
        • 1970-01-01
        • 2013-10-31
        相关资源
        最近更新 更多