Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if an object from an array has a specific format

So i have an array of objects named: tokens. Each object from this array has this format: {tokenName: string}. I want to test if each element from this array has the exact same format or else throw an error.

I have tried this:

for (let i = 0; i < tokens.length; i++) {
          if (
            typeof tokens[i].tokenName === "string" &&
            tokens[i].hasOwnProperty("tokenName")
          ) {
            // do stuff
          } else {
            throw new Error("Invalid array format");
 }

But it won’t pass the test.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use every to iterate over the array of objects, and apply the test to each object.

In this example tokens1 all objects have the tokenName key, and all are strings. tokens2 has one value that is an integer. tokens3 has a tokenAge key.

const tokens1=[{tokenName:"name1"},{tokenName:"name2"},{tokenName:"name3"},{tokenName:"name4"}],tokens2=[{tokenName:"name1"},{tokenName:"name2"},{tokenName:9},{tokenName:"name4"}],tokens3=[{tokenName:"name1"},{tokenName:"name2"},{tokenAge:"name3"},{tokenName:"name4"}];

// Accept an array of objects
function checkTokenName(tokens) {
  
  // Check the every token object in the
  // array passes the condition - true if it
  // does, false if it doesn't
  return tokens.every(token => {
    return (
      token.hasOwnProperty('tokenName')
      && typeof token.tokenName === 'string'
    );
  });
}

console.log(checkTokenName(tokens1));
console.log(checkTokenName(tokens2));
console.log(checkTokenName(tokens3));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading