user14241810
user14241810

Reputation:

a better way to loop through an array of items

I have a model that looks as follows

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}

the only objects in the Model that will always have a value is Id and Time.

i have an if statement that goes through each off my objects to check if its null as follows:

    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
                }

so i want to check if all the objects are null except time and ID, is there a better way of doing this than me using the above method in an if statement?

Upvotes: 2

Views: 90

Answers (4)

Leonardo Gasparini
Leonardo Gasparini

Reputation: 109

Well, you have two options in this case:

  1. Put your loop in a function to separate this logic to your model:
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. Use Object.values and every to check your properties as an array.
let report = {
  property1: null,
  property2: null,
}

let result = !Object.values(report).every(o => o === null);

console.log(result);

Upvotes: -1

Orelsanpls
Orelsanpls

Reputation: 23515

I would create a function to check about that using Object.entries and Array.every.

Perks of this solution :

  • Reusable utility function.
  • Works with any number of keys to ignore.
  • The typing of the function will throw an error in case you specify a key to ignore that is not a part of the provided object.

Playground in TypeScript


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

Upvotes: 0

Sarmad Hadi
Sarmad Hadi

Reputation: 57

for (let prop in Modal) {
    if (Modal.prop != time && Modal.prop != id && Modal[prop] != null) {
        return false
    }
    
}
return true

Return true if all properties except ID and Time are null.

Upvotes: 0

user13258211
user13258211

Reputation:

After playing around a bit, I came up with a solution using 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

Upvotes: 0

Related Questions