0

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.

3
  • 1
    hasOwnProperty - you’re missing a T Commented Nov 20, 2022 at 14:44
  • Well what exactly goes wrong? What happens that you don't expect? Commented Nov 20, 2022 at 14:46
  • If I pass an array with that specific format, it throws the error. Commented Nov 20, 2022 at 14:47

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.