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

Time:11-21

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.

CodePudding user response:

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

CodePudding user response:

hasOwnProperty is misspelled . Also the if condition should first check the property if it exists and then check typeof like

tokens[i].hasOwnProperty("tokenName") &&
typeof tokens[i].tokenName === "string" 
  • Related