Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65902494/a-better-way-to-loop-through-an-array-of-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...